Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

docs: enhance reference documentation for all modules

KaifAhmad1a8edbfbfb324
diff --git a/docs/reference/conflicts.md b/docs/reference/conflicts.md
new file mode 100644
index 00000000..437e0137
--- /dev/null
+++ b/docs/reference/conflicts.md
@@ -0,0 +1,286 @@
+# Conflicts
+
+> **Comprehensive conflict detection and resolution system for managing data discrepancies across multiple sources.**
+
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-alert-decagram:{ .lg .middle } **Multi-Source Detection**
+
+ ---
+
+ Detect conflicts across values, types, relationships, and temporal data
+
+- :material-scale-balance:{ .lg .middle } **Resolution Strategies**
+
+ ---
+
+ Resolve using voting, credibility, recency, or confidence scores
+
+- :material-chart-line:{ .lg .middle } **Conflict Analysis**
+
+ ---
+
+ Analyze patterns, trends, and severity of data discrepancies
+
+- :material-source-branch:{ .lg .middle } **Source Tracking**
+
+ ---
+
+ Track data provenance and source credibility
+
+- :material-clipboard-check:{ .lg .middle } **Investigation Guides**
+
+ ---
+
+ Generate automated guides for manual conflict resolution
+
+- :material-history:{ .lg .middle } **Traceability**
+
+ ---
+
+ Maintain full traceability of resolution decisions
+
+</div>
+
+!!! tip "When to Use"
+ - **Data Integration**: When merging data from multiple sources with overlapping entities
+ - **Quality Assurance**: To identify inconsistent data in your knowledge graph
+ - **Truth Maintenance**: To establish a "single source of truth" from noisy data
+
+---
+
+## ⚙️ Algorithms Used
+
+### Conflict Detection
+- **Value Comparison**: Equality checking with type normalization
+- **Type Mismatch**: Entity type hierarchy validation
+- **Temporal Analysis**: Timestamp comparison for time-based conflicts
+- **Logical Consistency**: Rule-based validation (e.g., "Person cannot be Organization")
+- **Severity Calculation**: Multi-factor scoring based on:
+ - Property importance weights
+ - Value difference magnitude
+ - Number of conflicting sources
+
+### Conflict Resolution
+- **Voting (Majority Rule)**: `max(frequency(values))` using Counter
+- **Credibility Weighted**: `Σ(value_i * source_credibility_i) / Σ(source_credibility)`
+- **Temporal Selection**: Select value with latest timestamp (`max(timestamp)`)
+- **Confidence Selection**: Select value with highest extraction confidence
+- **Hybrid Resolution**: Waterfall approach (e.g., Voting -> Credibility -> Recency)
+
+### Analysis & Tracking
+- **Pattern Identification**: Frequency analysis of conflict types
+- **Credibility Scoring**: Historical accuracy tracking per source
+- **Traceability**: Graph-based lineage of values and decisions
+
+---
+
+## Main Classes
+
+### ConflictDetector
+
+Detects conflicts across entities and properties.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `detect_conflicts(entities)` | Detect all conflicts | Multi-pass detection |
+| `detect_value_conflicts(entities, prop)` | Check specific property | Value comparison |
+| `detect_type_conflicts(entities)` | Check entity types | Hierarchy validation |
+| `detect_temporal_conflicts(entities)` | Check timestamps | Time-series analysis |
+
+**Example:**
+
+```python
+from semantica.conflicts import ConflictDetector
+
+detector = ConflictDetector()
+conflicts = detector.detect_conflicts([
+ {"id": "1", "name": "Apple", "source": "doc1"},
+ {"id": "1", "name": "Apple Inc.", "source": "doc2"}
+])
+
+for conflict in conflicts:
+ print(f"Conflict on {conflict.property_name}: {conflict.values}")
+```
+
+### ConflictResolver
+
+Resolves detected conflicts using configured strategies.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `resolve_conflicts(conflicts)` | Resolve list of conflicts | Strategy pattern |
+| `resolve_by_voting(conflict)` | Majority vote | Frequency counting |
+| `resolve_by_credibility(conflict)` | Source credibility | Weighted average |
+| `resolve_by_recency(conflict)` | Newest value | Timestamp comparison |
+
+**Example:**
+
+```python
+from semantica.conflicts import ConflictResolver
+
+resolver = ConflictResolver(default_strategy="credibility_weighted")
+results = resolver.resolve_conflicts(conflicts)
+
+for result in results:
+ print(f"Resolved {result.property}: {result.resolved_value}")
+ print(f"Strategy used: {result.strategy}")
+```
+
+### SourceTracker
+
+Tracks source information and credibility scores.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `track_source(entity, source)` | Register source for entity |
+| `get_source_credibility(source_id)` | Get current credibility score |
+| `update_credibility(source_id, score)` | Update source score |
+
+**Example:**
+
+```python
+from semantica.conflicts import SourceTracker
+
+tracker = SourceTracker()
+tracker.update_credibility("reliable_source", 0.9)
+tracker.update_credibility("noisy_source", 0.4)
+```
+
+### InvestigationGuideGenerator
+
+Generates human-readable guides for manual resolution.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `generate_guide(conflict)` | Create investigation steps |
+| `generate_checklist(conflicts)` | Create bulk checklist |
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.conflicts import detect_and_resolve
+
+# One-line detection and resolution
+conflicts, results = detect_and_resolve(
+ entities,
+ property_name="revenue",
+ resolution_strategy="credibility_weighted"
+)
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+export CONFLICT_DEFAULT_STRATEGY=voting
+export CONFLICT_SIMILARITY_THRESHOLD=0.85
+export CONFLICT_AUTO_RESOLVE=true
+```
+
+### YAML Configuration
+
+```yaml
+conflicts:
+ default_strategy: voting
+ auto_resolve: true
+
+ strategies:
+ voting:
+ min_votes: 2
+ credibility:
+ default_score: 0.5
+
+ weights:
+ name: 1.0
+ description: 0.5
+ date: 0.8
+```
+
+---
+
+## Integration Examples
+
+### Pipeline Integration
+
+```python
+from semantica.conflicts import detect_and_resolve
+from semantica.ingest import Ingestor
+
+# 1. Ingest from multiple sources
+ingestor = Ingestor()
+data1 = ingestor.ingest("source1.pdf")
+data2 = ingestor.ingest("source2.html")
+
+# 2. Combine entities (assuming same IDs)
+combined_entities = data1.entities + data2.entities
+
+# 3. Resolve conflicts
+conflicts, resolutions = detect_and_resolve(
+ combined_entities,
+ resolution_strategy="credibility_weighted",
+ source_credibility={
+ "source1.pdf": 0.9,
+ "source2.html": 0.6
+ }
+)
+
+# 4. Apply resolutions
+for resolution in resolutions:
+ print(f"Final value for {resolution.entity_id}: {resolution.resolved_value}")
+```
+
+---
+
+## Best Practices
+
+1. **Define Source Credibility**: Always assign credibility scores to your sources if possible.
+2. **Use Hybrid Strategies**: Voting is good for categorical data, Recency for temporal data.
+3. **Keep Humans in the Loop**: Use `InvestigationGuideGenerator` for high-severity conflicts.
+4. **Normalize First**: Ensure data is normalized (dates, numbers) before conflict detection to avoid false positives.
+
+---
+
+## Troubleshooting
+
+**Issue**: Too many false positives on string fields.
+**Solution**: Enable fuzzy matching or increase similarity threshold.
+
+```python
+detector = ConflictDetector(
+ string_similarity_threshold=0.9, # Stricter matching
+ ignore_case=True
+)
+```
+
+**Issue**: Resolution favoring wrong source.
+**Solution**: Check and adjust source credibility scores.
+
+```python
+tracker.update_credibility("bad_source", 0.1)
+```
+
+---
+
+## See Also
+
+- [Deduplication Module](deduplication.md) - For merging duplicate entities
+- [Normalize Module](normalize.md) - For pre-processing data
+- [KG QA Module](kg_qa.md) - For overall graph quality
diff --git a/docs/reference/context.md b/docs/reference/context.md
new file mode 100644
index 00000000..10d2a163
--- /dev/null
+++ b/docs/reference/context.md
@@ -0,0 +1,265 @@
+# Context
+
+> **Context engineering and memory management system for intelligent agents using RAG and Knowledge Graphs.**
+
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-graph:{ .lg .middle } **Context Graph**
+
+ ---
+
+ Build dynamic context graphs from conversations and entities
+
+- :material-brain:{ .lg .middle } **Agent Memory**
+
+ ---
+
+ Persistent memory management with vector storage integration
+
+- :material-link-variant:{ .lg .middle } **Entity Linking**
+
+ ---
+
+ Link entities across documents and conversations
+
+- :material-magnify:{ .lg .middle } **Hybrid Retrieval**
+
+ ---
+
+ Retrieve context using Vector + Graph + Keyword search
+
+- :material-history:{ .lg .middle } **Conversation History**
+
+ ---
+
+ Manage and synthesize conversation history
+
+- :material-bullseye-arrow:{ .lg .middle } **Intent Analysis**
+
+ ---
+
+ Extract and track user intent and sentiment
+
+</div>
+
+!!! tip "When to Use"
+ - **Agent Development**: When building agents that need long-term memory
+ - **RAG Applications**: For advanced Retrieval-Augmented Generation
+ - **Personalization**: To maintain user-specific context and preferences
+
+---
+
+## ⚙️ Algorithms Used
+
+### Context Graph Construction
+- **Graph Building**: Node/Edge construction from extracted entities
+- **Graph Traversal**: BFS/DFS for multi-hop context discovery
+- **Intent Extraction**: NLP-based intent classification
+- **Sentiment Analysis**: Sentiment scoring and extraction
+
+### Agent Memory
+- **Vector Embedding**: Dense vector generation for memory items
+- **Vector Search**: Cosine similarity search (k-NN)
+- **Retention Policy**: Time-based decay and cleanup
+- **Memory Indexing**: Deque-based sliding window for short-term memory
+
+### Entity Linking
+- **URI Generation**: Hash-based deterministic IDs
+- **Text Similarity**: Jaccard/Levenshtein for name matching
+- **Graph Lookup**: Entity resolution against Knowledge Graph
+- **Bidirectional Linking**: Symmetric link creation
+
+### Context Retrieval
+- **Hybrid Scoring**: `α * VectorScore + β * GraphScore + γ * KeywordScore`
+- **Graph Expansion**: Retrieving neighbors of retrieved entities
+- **Deduplication**: Content-based result merging
+- **Result Ranking**: Weighted aggregation of scores
+
+---
+
+## Main Classes
+
+### ContextGraphBuilder
+
+Builds and manages the context graph.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `build_from_entities(entities)` | Build graph from entities | Node creation |
+| `add_conversation(conv)` | Add conversation data | Intent/Entity extraction |
+| `get_subgraph(node_id)` | Get local context | BFS Traversal |
+
+**Example:**
+
+```python
+from semantica.context import ContextGraphBuilder
+
+builder = ContextGraphBuilder()
+graph = builder.build_from_entities_and_relationships(
+ entities=extracted_entities,
+ relationships=extracted_rels
+)
+```
+
+### AgentMemory
+
+Manages persistent agent memory.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `store(text, metadata)` | Store memory item | Embedding + Vector Store |
+| `retrieve(query)` | Retrieve relevant memories | Vector Similarity |
+| `prune(days)` | Remove old memories | Time-based filtering |
+
+**Example:**
+
+```python
+from semantica.context import AgentMemory
+
+memory = AgentMemory(vector_store=vs, knowledge_graph=kg)
+memory.store("User prefers Python over Java", metadata={"type": "preference"})
+relevant = memory.retrieve("What language does the user like?")
+```
+
+### EntityLinker
+
+Links entities across different contexts.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `link_entities(entities)` | Link list of entities | Similarity matching |
+| `generate_uri(entity)` | Create unique ID | Hashing |
+| `find_links(entity)` | Find related entities | Graph lookup |
+
+### ContextRetriever
+
+Orchestrates hybrid retrieval.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `retrieve(query)` | Get full context | Hybrid (Vector+Graph) |
+| `retrieve_from_graph(query)` | Graph-only retrieval | Traversal |
+| `retrieve_from_memory(query)` | Memory-only retrieval | Vector search |
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.context import build_context
+
+# Build context and memory in one go
+context = build_context(
+ entities=entities,
+ relationships=relationships,
+ vector_store=vs,
+ knowledge_graph=kg,
+ store_initial_memories=True
+)
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+export CONTEXT_RETENTION_DAYS=30
+export CONTEXT_MAX_HOPS=2
+export CONTEXT_EMBEDDING_MODEL=all-MiniLM-L6-v2
+```
+
+### YAML Configuration
+
+```yaml
+context:
+ retention_policy:
+ max_days: 30
+ max_items: 1000
+
+ retrieval:
+ hybrid_weights:
+ vector: 0.6
+ graph: 0.3
+ keyword: 0.1
+
+ graph:
+ max_depth: 2
+ include_attributes: true
+```
+
+---
+
+## Integration Examples
+
+### Chatbot with Memory
+
+```python
+from semantica.context import AgentMemory, ContextRetriever
+from semantica.llm import LLMClient
+
+# 1. Initialize
+memory = AgentMemory(vector_store=vs)
+retriever = ContextRetriever(memory=memory, graph=kg)
+llm = LLMClient()
+
+def chat(user_input):
+ # 2. Retrieve Context
+ context = retriever.retrieve(user_input)
+
+ # 3. Generate Response
+ response = llm.generate(user_input, context=context)
+
+ # 4. Update Memory
+ memory.store(f"User: {user_input}")
+ memory.store(f"Agent: {response}")
+
+ return response
+```
+
+---
+
+## Best Practices
+
+1. **Prune Regularly**: Use retention policies to keep memory relevant and performant.
+2. **Use Hybrid Retrieval**: Relying solely on vector search misses structural relationships; use graph context too.
+3. **Enrich Metadata**: Store rich metadata (timestamp, source, type) with memories for better filtering.
+4. **Link Entities**: Ensure `EntityLinker` is used to connect mentions of the same entity across conversations.
+
+---
+
+## Troubleshooting
+
+**Issue**: Retrieval returns irrelevant old memories.
+**Solution**: Adjust retention policy or increase vector similarity threshold.
+
+```python
+memory = AgentMemory(
+ retention_days=7,
+ similarity_threshold=0.8
+)
+```
+
+**Issue**: Context graph growing too large.
+**Solution**: Use `prune_graph` or limit hop depth during retrieval.
+
+---
+
+## See Also
+
+- [Vector Store Module](vector_store.md) - Underlying storage for memory
+- [Knowledge Graph Module](kg.md) - Underlying graph structure
+- [Embeddings Module](embeddings.md) - Vector generation
diff --git a/docs/reference/core.md b/docs/reference/core.md
index d4bd2ef5..e69585fb 100644
--- a/docs/reference/core.md
+++ b/docs/reference/core.md
@@ -1,6 +1,6 @@
-# Core Module
+# Core
-> **The heart of Semantica - orchestrating all framework components with configuration, lifecycle, and plugin management.**
+> **Framework infrastructure, lifecycle management, and plugin system.**
---
@@ -8,420 +8,181 @@
<div class="grid cards" markdown>
-- :material-cog-outline:{ .lg .middle } **Framework Orchestration**
+- :material-cogs:{ .lg .middle } **Orchestrator**
---
- Main `Semantica` class coordinating all operations and modules
+ Central coordinator for all framework components and workflows
-- :material-file-cog:{ .lg .middle } **Configuration Management**
+- :material-lifecycle:{ .lg .middle } **Lifecycle Management**
---
- Centralized config with YAML/JSON support and validation
+ Manage initialization, startup, shutdown, and state transitions
-- :material-timeline:{ .lg .middle } **Lifecycle Management**
+- :material-tune:{ .lg .middle } **Configuration**
---
- Startup, shutdown, health monitoring with hook system
+ Unified configuration management via YAML and Environment variables
- :material-puzzle:{ .lg .middle } **Plugin System**
---
- Dynamic plugin discovery, loading, and isolation
+ Extensible plugin registry for adding custom modules and capabilities
-- :material-registry:{ .lg .middle } **Method Registry**
+- :material-console:{ .lg .middle } **Logging & Telemetry**
---
- Extensible method registration for custom implementations
-
-- :material-api:{ .lg .middle } **Convenience API**
-
- ---
-
- Simple `build()` function for quick knowledge base creation
+ Centralized logging and metrics collection
</div>
-!!! example "Quick Start"
- ```python
- from semantica import Semantica
-
- # One-liner to build knowledge base
- semantica = Semantica()
- result = semantica.build_knowledge_base(["documents/"])
-
- print(f"Nodes: {result['knowledge_graph'].node_count}")
- ```
+!!! tip "When to Use"
+ - **Application Startup**: Initializing the Semantica framework in your app
+ - **Configuration**: Tuning global settings
+ - **Extension**: Developing custom plugins or modules
+ - **Orchestration**: Coordinating complex workflows across multiple modules
---
## ⚙️ Algorithms Used
-### Configuration Management
-- **YAML/JSON Parsing**: Configuration file parsing with schema validation
-- **Environment Variable Substitution**: `${VAR_NAME}` pattern replacement
-- **Configuration Merging**: Deep merge algorithm for layered configs
-- **Validation**: JSON Schema validation for type checking
-
### Lifecycle Management
-- **Hook System**: Observer pattern for lifecycle events
-- **Health Monitoring**: Periodic health checks with exponential backoff
-- **Graceful Shutdown**: Resource cleanup with timeout handling
+- **State Machine**: `CREATED` -> `INITIALIZED` -> `RUNNING` -> `STOPPED`
+- **Dependency Injection**: Resolving and injecting dependencies between modules.
+- **Graceful Shutdown**: Ensuring all resources (DB connections, thread pools) are closed properly.
+
+### Configuration
+- **Layered Loading**: Defaults -> Config File -> Environment Variables -> CLI Arguments (Priority order).
+- **Schema Validation**: Validating config structure against defined schemas.
### Plugin System
-- **Discovery**: File system scanning for plugin modules
-- **Loading**: Dynamic import with dependency resolution
-- **Isolation**: Separate namespace for each plugin
+- **Discovery**: Auto-discovery of plugins via entry points or directory scanning.
+- **Registration**: Dynamic registration of classes and functions.
+- **Hook Execution**: Running plugin hooks at specific lifecycle events.
---
## Main Classes
-### Semantica
+### Orchestrator
+The brain of the framework.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `__init__(config)` | Initialize framework | Configuration loading + validation |
-| `build_knowledge_base(sources)` | Build knowledge graph | Orchestrate ingest → parse → extract → build |
-| `run_pipeline(pipeline_config)` | Execute custom pipeline | DAG execution with error handling |
-| `shutdown()` | Graceful shutdown | Resource cleanup with lifecycle hooks |
-| `get_health_status()` | Get system health | Component health aggregation |
-
-**Example:**
-
-```python
-from semantica import Semantica
-
-# Initialize with default config
-semantica = Semantica()
-
-# Build knowledge base
-result = semantica.build_knowledge_base(
- sources=["documents/"],
- extract_entities=True,
- extract_relations=True,
- embeddings=True,
- graph=True
-)
-
-kg = result["knowledge_graph"]
-print(f"Nodes: {kg.node_count}, Edges: {kg.edge_count}")
-
-# Shutdown
-semantica.shutdown()
-```
-
----
-
-### Config
-
-
-**Configuration Structure:**
-
-```python
-@dataclass
-class Config:
- llm: Optional[Dict[str, Any]] = None
- embeddings: Optional[Dict[str, Any]] = None
- knowledge_graph: Optional[Dict[str, Any]] = None
- vector_store: Optional[Dict[str, Any]] = None
- # ... other configuration fields
-```
+| Method | Description |
+|--------|-------------|
+| `start()` | Initialize and start all components |
+| `stop()` | Graceful shutdown |
+| `get_component(name)` | Access initialized module |
**Example:**
```python
-from semantica.core import Config
+from semantica.core import Orchestrator
-config = Config(
- llm={"provider": "openai", "model": "gpt-4"},
- embeddings={"provider": "openai", "model": "text-embedding-3-large"},
- knowledge_graph={"merge_entities": True, "resolve_conflicts": True}
-)
+app = Orchestrator()
+app.start()
-semantica = Semantica(config=config)
+# Access modules
+kg = app.get_component("knowledge_graph")
+ingest = app.get_component("ingest")
```
----
-
### ConfigManager
+Manages global configuration.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `load_config(path)` | Load configuration file | YAML/JSON parsing + validation |
-| `validate_config(config)` | Validate configuration | JSON Schema validation |
-| `get(key, default)` | Get config value | Nested key lookup with dot notation |
-| `set(key, value)` | Set config value | Nested key assignment |
-| `merge_configs(configs)` | Merge multiple configs | Deep merge algorithm |
-
-**Example:**
-
-```python
-from semantica.core import ConfigManager
-
-manager = ConfigManager()
-
-# Load from file
-config = manager.load_config("config.yaml")
-
-# Validate
-is_valid, errors = manager.validate_config(config)
-
-# Get/set values
-llm_model = manager.get("llm.model", default="gpt-4")
-manager.set("llm.temperature", 0.7)
-```
-
----
-
-### LifecycleManager
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `startup()` | Execute startup sequence | Sequential hook execution |
-| `shutdown()` | Execute shutdown sequence | Reverse-order hook execution |
-| `register_hook(event, callback)` | Register lifecycle hook | Hook registration |
-| `get_health_status()` | Get system health | Component health aggregation |
-
-**Lifecycle Events:**
-- `on_startup`: Framework initialization
-- `on_shutdown`: Framework cleanup
-- `on_error`: Error handling
-- `on_health_check`: Health monitoring
-
-**Example:**
-
-```python
-from semantica.core import LifecycleManager
-
-manager = LifecycleManager()
-
-# Register hooks
-manager.register_hook("on_startup", lambda: print("Starting..."))
-manager.register_hook("on_shutdown", lambda: print("Shutting down..."))
-
-# Startup
-manager.startup()
-
-# Health check
-health = manager.get_health_status()
-print(f"Status: {health.status}, Components: {health.components}")
-
-# Shutdown
-manager.shutdown()
-```
-
----
+| Method | Description |
+|--------|-------------|
+| `load(path)` | Load config from file |
+| `get(key, default)` | Get config value |
### PluginRegistry
+Manages extensions.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `discover_plugins(path)` | Discover available plugins | File system scanning |
-| `load_plugin(name)` | Load plugin | Dynamic import + initialization |
-| `unload_plugin(name)` | Unload plugin | Cleanup + namespace removal |
-| `list_plugins()` | List loaded plugins | Plugin registry enumeration |
-| `get_plugin(name)` | Get plugin instance | Registry lookup |
-
-**Example:**
-
-```python
-from semantica.core import PluginRegistry
-
-registry = PluginRegistry()
-
-# Discover plugins
-registry.discover_plugins("plugins/")
-
-# Load plugin
-registry.load_plugin("custom_extractor")
-
-# Use plugin
-plugin = registry.get_plugin("custom_extractor")
-result = plugin.extract(text)
-
-# Unload
-registry.unload_plugin("custom_extractor")
-```
+| Method | Description |
+|--------|-------------|
+| `register(plugin)` | Register new plugin |
+| `get_plugin(name)` | Retrieve plugin |
---
-## Convenience Functions
-
-### build()
-
+## Configuration
-**Signature:**
-```python
-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]
-```
-
-**Example:**
+### Environment Variables
-```python
-from semantica.core import build
-
-# Simple one-liner
-result = build(sources=["documents/"])
-
-# With options
-result = build(
- sources=["documents/"],
- extract_entities=True,
- extract_relations=True,
- embeddings=True,
- graph=True,
- llm_provider="openai",
- llm_model="gpt-4"
-)
+```bash
+export SEMANTICA_ENV=production
+export SEMANTICA_LOG_LEVEL=INFO
+export SEMANTICA_CONFIG_PATH=./config.yaml
```
----
-
-## Configuration Reference
+### YAML Configuration
```yaml
-# config.yaml - Complete Configuration Example
-
-# LLM Configuration
-llm:
- provider: openai # openai, anthropic, google, groq, ollama
- model: gpt-4
- temperature: 0.1
- max_tokens: 4000
- api_key: ${OPENAI_API_KEY}
-
-# Embeddings Configuration
-embeddings:
- provider: openai
- model: text-embedding-3-large
- dimensions: 3072
- batch_size: 100
-
-# Knowledge Graph Configuration
-knowledge_graph:
- merge_entities: true
- entity_resolution_strategy: fuzzy
- similarity_threshold: 0.85
- resolve_conflicts: true
- enable_temporal: true
-
-# Vector Store Configuration
-vector_store:
- backend: faiss
- index_type: HNSW
- metric: cosine
- dimension: 3072
-
-# Pipeline Configuration
-pipeline:
- parallel: true
- max_workers: 4
- error_handling: retry
- max_retries: 3
-
-# Logging Configuration
-logging:
- level: INFO
- format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
- handlers:
- - console
- - file
+core:
+ environment: production
+ log_level: INFO
+ plugins:
+ enabled: true
+ directory: ./plugins
```
---
-## Common Patterns
-
-### Pattern 1: Basic Usage
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-result = semantica.build_knowledge_base(["documents/"])
-kg = result["knowledge_graph"]
-```
+## Integration Examples
-### Pattern 2: Custom Configuration
+### Custom Application
```python
-from semantica import Semantica, Config
-
-config = Config(
- llm={"provider": "openai", "model": "gpt-4"},
- embeddings={"provider": "openai", "model": "text-embedding-3-large"}
-)
+from semantica.core import Orchestrator, ConfigManager
-semantica = Semantica(config=config)
-result = semantica.build_knowledge_base(["documents/"])
-```
+# 1. Load Config
+config = ConfigManager()
+config.load("config.yaml")
-### Pattern 3: Pipeline Execution
+# 2. Initialize Orchestrator
+app = Orchestrator(config=config)
-```python
-from semantica import Semantica
+# 3. Register Custom Plugin
+class MyPlugin:
+ name = "my_plugin"
+ def initialize(self):
+ print("My Plugin Started")
-semantica = Semantica()
+app.plugin_registry.register(MyPlugin())
-pipeline_config = {
- "steps": [
- {"name": "ingest", "type": "FileIngestor"},
- {"name": "parse", "type": "DocumentParser"},
- {"name": "extract", "type": "NERExtractor"},
- {"name": "build_kg", "type": "GraphBuilder"}
- ]
-}
+# 4. Start
+app.start()
-result = semantica.run_pipeline(pipeline_config)
+# 5. Run Workload
+try:
+ app.run_pipeline("my_pipeline")
+finally:
+ app.stop()
```
---
-## Error Handling
+## Best Practices
-```python
-from semantica import Semantica
-from semantica.core import ConfigurationError, PipelineError
-
-try:
- semantica = Semantica(config="invalid_config.yaml")
-except ConfigurationError as e:
- print(f"Configuration error: {e}")
-
-try:
- result = semantica.build_knowledge_base([])
-except PipelineError as e:
- print(f"Pipeline error: {e}")
-```
+1. **Use Orchestrator**: Avoid manually instantiating every module; let the Orchestrator handle dependencies.
+2. **Graceful Shutdown**: Always ensure `app.stop()` is called (e.g., in a `finally` block) to prevent resource leaks.
+3. **Config Layers**: Use `config.yaml` for defaults and Environment Variables for secrets/overrides.
---
## See Also
-- [Pipeline Module](pipeline.md) - Pipeline building and execution
-- [Knowledge Graph Module](kg.md) - Graph construction
-- [Semantic Extract Module](semantic_extract.md) - Entity extraction
+- [Pipeline Module](pipeline.md) - Executed by the Orchestrator
+- [Utils Module](utils.md) - Shared utilities used by Core
diff --git a/docs/reference/deduplication.md b/docs/reference/deduplication.md
new file mode 100644
index 00000000..f821ee8a
--- /dev/null
+++ b/docs/reference/deduplication.md
@@ -0,0 +1,261 @@
+# Deduplication
+
+> **Advanced entity deduplication and resolution system for maintaining a clean, single-source-of-truth Knowledge Graph.**
+
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-content-duplicate:{ .lg .middle } **Duplicate Detection**
+
+ ---
+
+ Identify duplicates using multi-factor similarity metrics
+
+- :material-set-merge:{ .lg .middle } **Entity Merging**
+
+ ---
+
+ Merge entities with configurable strategies (Keep First, Most Complete, etc.)
+
+- :material-group:{ .lg .middle } **Clustering**
+
+ ---
+
+ Cluster similar entities for efficient batch processing
+
+- :material-calculator:{ .lg .middle } **Similarity Metrics**
+
+ ---
+
+ Levenshtein, Jaro-Winkler, Cosine, and Jaccard similarity support
+
+- :material-history:{ .lg .middle } **Provenance**
+
+ ---
+
+ Preserve data lineage and history during merges
+
+- :material-scale:{ .lg .middle } **Scalable**
+
+ ---
+
+ Batch processing and blocking for large datasets
+
+</div>
+
+!!! tip "When to Use"
+ - **Data Ingestion**: Clean incoming data before adding to the graph
+ - **Graph Maintenance**: Periodically clean up existing knowledge graphs
+ - **Entity Resolution**: Resolve entities from different sources (e.g., "Apple" vs "Apple Inc.")
+
+---
+
+## ⚙️ Algorithms Used
+
+### Similarity Calculation
+- **Levenshtein Distance**: Edit distance for string difference
+- **Jaro-Winkler**: String similarity with prefix weighting (good for names)
+- **Cosine Similarity**: Vector similarity for embeddings
+- **Jaccard Similarity**: Set overlap for properties/relationships
+- **Multi-factor Aggregation**: Weighted sum of multiple metrics
+
+### Duplicate Detection
+- **Pairwise Comparison**: O(n²) comparison (for small sets)
+- **Blocking/Indexing**: Reduce search space for large sets
+- **Union-Find**: Disjoint set data structure for grouping duplicates
+- **Confidence Scoring**: `0.0 - 1.0` probability score for duplicates
+
+### Clustering
+- **Hierarchical Clustering**: Agglomerative bottom-up clustering
+- **Connected Components**: Graph-based cluster detection
+- **Cluster Quality**: Cohesion and separation metrics
+
+### Entity Merging
+- **Strategy Pattern**: Pluggable merge logic
+- **Property Union**: Combining unique properties
+- **Relationship Merging**: Re-linking relationships to the merged entity
+
+---
+
+## Main Classes
+
+### DuplicateDetector
+
+Identifies potential duplicates in a dataset.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `detect_duplicates(entities)` | Find duplicate pairs | Pairwise/Blocking |
+| `detect_duplicate_groups(entities)` | Find clusters of duplicates | Union-Find |
+
+**Example:**
+
+```python
+from semantica.deduplication import DuplicateDetector
+
+detector = DuplicateDetector(similarity_threshold=0.85)
+duplicates = detector.detect_duplicates(entities)
+
+for group in duplicates:
+ print(f"Found group of {len(group)} duplicates")
+```
+
+### EntityMerger
+
+Merges duplicate entities into a single canonical entity.
+
+**Methods:**
+
+| Method | Description | Strategy |
+|--------|-------------|----------|
+| `merge_duplicates(entities)` | Execute merge | Configured Strategy |
+| `merge_group(group)` | Merge specific group | Configured Strategy |
+
+**Strategies:**
+- `KEEP_FIRST`: Keep the first entity encountered
+- `KEEP_MOST_COMPLETE`: Keep entity with most properties
+- `KEEP_HIGHEST_CONFIDENCE`: Keep entity with highest confidence score
+- `MERGE_ALL`: Create new entity combining all info
+
+**Example:**
+
+```python
+from semantica.deduplication import EntityMerger
+
+merger = EntityMerger(strategy="keep_most_complete")
+result = merger.merge_duplicates(entities)
+```
+
+### SimilarityCalculator
+
+Calculates similarity between entities.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `calculate(e1, e2)` | Get aggregate score |
+| `string_similarity(s1, s2)` | Text comparison |
+
+### ClusterBuilder
+
+Builds clusters for batch processing.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `build_clusters(entities)` | Create clusters | Hierarchical/Graph |
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.deduplication import deduplicate
+
+# Detect and merge in one step
+result = deduplicate(
+ entities,
+ similarity_threshold=0.8,
+ merge_strategy="keep_most_complete"
+)
+
+print(f"Reduced {result['statistics']['reduction']} entities")
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+export DEDUP_SIMILARITY_THRESHOLD=0.8
+export DEDUP_MERGE_STRATEGY=keep_most_complete
+export DEDUP_BLOCKING_ENABLED=true
+```
+
+### YAML Configuration
+
+```yaml
+deduplication:
+ thresholds:
+ similarity: 0.8
+ confidence: 0.7
+
+ weights:
+ name: 0.6
+ type: 0.2
+ attributes: 0.2
+
+ blocking:
+ enabled: true
+ method: "token_blocking"
+```
+
+---
+
+## Integration Examples
+
+### Ingestion Pipeline
+
+```python
+from semantica.ingest import Ingestor
+from semantica.deduplication import deduplicate
+from semantica.kg import KnowledgeGraph
+
+# 1. Ingest
+ingestor = Ingestor()
+raw_entities = ingestor.ingest_batch(files)
+
+# 2. Deduplicate
+dedup_result = deduplicate(
+ raw_entities,
+ similarity_threshold=0.85,
+ merge_strategy="merge_all"
+)
+
+# 3. Load to KG
+kg = KnowledgeGraph()
+kg.add_entities(dedup_result['merged_entities'])
+```
+
+---
+
+## Best Practices
+
+1. **Block First**: For >1000 entities, enable blocking to avoid O(n²) performance.
+2. **Tune Thresholds**: Start with 0.85 and adjust based on false positive/negative rates.
+3. **Preserve Provenance**: Keep `preserve_provenance=True` to track where merged data came from.
+4. **Normalize**: Run `normalize` module before deduplication for best results.
+
+---
+
+## Troubleshooting
+
+**Issue**: Merging "Apple" and "Apple Pie" (False Positive).
+**Solution**: Increase threshold or use Jaro-Winkler which penalizes prefix mismatches.
+
+```python
+detector = DuplicateDetector(
+ similarity_method="jaro_winkler",
+ similarity_threshold=0.9
+)
+```
+
+**Issue**: Slow performance on large datasets.
+**Solution**: Use `ClusterBuilder` with blocking.
+
+---
+
+## See Also
+
+- [Conflicts Module](conflicts.md) - Handling conflicting values during merge
+- [Normalize Module](normalize.md) - Pre-processing for better matching
+- [Knowledge Graph Module](kg.md) - Target for deduplicated data
diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.md
index 12bce2ab..47e638b6 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,134 @@
### 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 build, embed_text, calculate_similarity
-embedder = MultimodalEmbedder(
- model="openai/clip-vit-base-patch32",
- fusion_strategy="weighted_sum",
- text_weight=0.6
-)
+# One-line generation
+result = build(["text1", "text2"])
-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(vec1, vec2)
```
---
-### 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/evals.md b/docs/reference/evals.md
index 7511bb4a..9ffe8ed6 100644
--- a/docs/reference/evals.md
+++ b/docs/reference/evals.md
@@ -1,8 +1,6 @@
-# Evals Module
+# Evals
-**Coming Soon**
-
----
-
-This module is under development and will be available in a future release.
+> **Evaluation framework for measuring Knowledge Graph quality, extraction accuracy, and pipeline performance.**
+!!! warning "Coming Soon"
+ This module is currently in active development. Documentation will be available soon.
diff --git a/docs/reference/export.md b/docs/reference/export.md
index 75020e67..e6f70180 100644
--- a/docs/reference/export.md
+++ b/docs/reference/export.md
@@ -1,4 +1,4 @@
-# Export Module
+# Export
> **Export knowledge graphs and data to multiple formats with W3C-compliant serialization.**
diff --git a/docs/reference/graph_store.md b/docs/reference/graph_store.md
index 5aa71998..93de9da3 100644
--- a/docs/reference/graph_store.md
+++ b/docs/reference/graph_store.md
@@ -1,6 +1,6 @@
-# Graph Store Module
+# Graph Store
-> **Store and query property graphs with support for Neo4j, KuzuDB, and FalkorDB backends.**
+> **Unified interface for Property Graph Databases (Neo4j, KuzuDB, FalkorDB).**
---
@@ -8,70 +8,67 @@
<div class="grid cards" markdown>
-- :material-graph:{ .lg .middle } **Property Graphs**
+- :material-database-search:{ .lg .middle } **Multi-Backend**
---
- Store nodes and relationships with properties using industry-standard graph databases
+ Support for Neo4j (Enterprise), KuzuDB (Embedded), and FalkorDB (Redis-based)
-- :material-database-search:{ .lg .middle } **Cypher Queries**
+- :material-code-braces:{ .lg .middle } **Cypher Support**
---
- Full Cypher/OpenCypher query language support for powerful graph queries
+ Execute standard Cypher queries across all supported backends
-- :material-lightning-bolt:{ .lg .middle } **Multiple Backends**
+- :material-graph:{ .lg .middle } **Graph Algorithms**
---
- Neo4j, KuzuDB, and FalkorDB support for different use cases
+ Built-in support for PageRank, Community Detection, and Path Finding
-- :material-transit-connection:{ .lg .middle } **Graph Traversal**
+- :material-flash:{ .lg .middle } **Bulk Loading**
---
- Efficient path finding and neighborhood traversal algorithms
+ Optimized batch processing for high-speed data ingestion
-- :material-chart-bubble:{ .lg .middle } **Graph Analytics**
+- :material-lock:{ .lg .middle } **Transactions**
---
- Centrality, shortest path, and community detection algorithms
+ ACID transaction support with rollback capabilities
-- :material-cog-transfer:{ .lg .middle } **Batch Operations**
+- :material-chart-bell-curve:{ .lg .middle } **Analytics**
---
- Efficient bulk insert with transaction support and progress tracking
+ Centrality, Similarity, and Connectivity analysis
</div>
-!!! tip "Choosing the Right Backend"
- - **Neo4j**: Production-grade, full-featured, best for enterprise applications
- - **KuzuDB**: Embedded database, excellent for analytics, no server required
- - **FalkorDB**: Ultra-fast, Redis-based, ideal for LLM applications and real-time queries
+!!! tip "When to Use"
+ - **Persistent Storage**: Storing the Knowledge Graph for long-term access
+ - **Complex Queries**: Running multi-hop pattern matching queries
+ - **Graph Analytics**: Performing global analysis on the graph structure
+ - **Production**: Scaling to billions of nodes/edges (Neo4j/FalkorDB)
---
## ⚙️ Algorithms Used
-### Graph Storage
-- **Adjacency List**: Node-relationship storage pattern
-- **Property Storage**: Key-value property management on nodes/relationships
-- **Index Structures**: B-tree and hash indexes for fast lookups
-- **Sparse Matrices**: FalkorDB uses sparse matrix representation for adjacency
-
-### Query Processing
-- **Pattern Matching**: Cypher MATCH clause processing
-- **Join Algorithms**: Hash join, merge join for multi-pattern queries
-- **Index Utilization**: Automatic index selection for optimal performance
-- **Query Planning**: Cost-based query optimization
+### Query Execution
+- **Cypher Translation**: Adapting queries for specific backend nuances (though most support OpenCypher).
+- **Query Optimization**: Index utilization and execution plan analysis.
### Graph Analytics
-- **Shortest Path**: Dijkstra's algorithm, BFS-based shortest path
-- **Centrality**: Degree centrality, betweenness centrality, PageRank
-- **Community Detection**: Label propagation, Louvain algorithm
-- **Traversal**: BFS/DFS graph traversal with depth control
+- **PageRank**: Measuring node importance based on incoming links.
+- **Louvain Modularity**: Detecting communities by optimizing modularity.
+- **Shortest Path**: Dijkstra/A* for finding optimal routes.
+- **Jaccard Similarity**: Measuring node similarity based on shared neighbors.
+
+### Bulk Operations
+- **Chunking**: Splitting large datasets into optimal batch sizes (e.g., 5000 records) to prevent memory overflow.
+- **Parallel Loading**: Concurrent batch insertion (backend dependent).
---
@@ -79,283 +76,67 @@
### GraphStore
-The main interface for working with property graph databases.
+The main facade for graph operations.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `create_node(labels, properties)` | Create a node | Index insertion |
-| `create_nodes(nodes)` | Batch create nodes | Bulk insertion with transactions |
-| `get_node(node_id)` | Get node by ID | Index lookup |
-| `get_nodes(labels, properties, limit)` | Query nodes | Pattern matching |
-| `update_node(node_id, properties, merge)` | Update node | Property merge/replace |
-| `delete_node(node_id, detach)` | Delete node | Cascade or isolated delete |
-| `create_relationship(start, end, type, props)` | Create relationship | Edge insertion |
-| `get_relationships(node_id, type, direction)` | Query relationships | Pattern matching |
-| `execute_query(cypher, params)` | Execute Cypher query | Full query processing |
-| `shortest_path(start, end, type, max_depth)` | Find shortest path | Dijkstra/BFS |
-| `get_neighbors(node_id, depth)` | Get neighborhood | BFS traversal |
-
-**Supported Backends:**
-
-| Backend | Query Language | Best For | Deployment |
-|---------|---------------|----------|------------|
-| **Neo4j** | Cypher | Enterprise, full features | Server/Cloud |
-| **KuzuDB** | Cypher | Analytics, embedded | Embedded |
-| **FalkorDB** | OpenCypher | LLM apps, real-time | Redis-based |
+| Method | Description |
+|--------|-------------|
+| `execute_query(query, params)` | Run Cypher query |
+| `create_node(labels, props)` | Add node |
+| `create_relationship(start, end, type)` | Add edge |
**Example:**
```python
from semantica.graph_store import GraphStore
-# Initialize with Neo4j backend
-store = GraphStore(
- backend="neo4j",
- uri="bolt://localhost:7687",
- user="neo4j",
- password="password"
-)
-
-# Connect to database
-store.connect()
-
-# Create nodes
-alice = store.create_node(
- labels=["Person"],
- properties={"name": "Alice", "age": 30}
-)
-
-bob = store.create_node(
- labels=["Person"],
- properties={"name": "Bob", "age": 25}
-)
-
-# Create relationship
-store.create_relationship(
- start_node_id=alice["id"],
- end_node_id=bob["id"],
- rel_type="KNOWS",
- properties={"since": 2020}
-)
-
-# Query the graph
-results = store.execute_query(
- "MATCH (p:Person) WHERE p.age > $min_age RETURN p.name, p.age",
- parameters={"min_age": 20}
+store = GraphStore(backend="neo4j")
+store.execute_query(
+ "MATCH (n:Person {name: $name}) RETURN n",
+ params={"name": "Alice"}
)
-
-for record in results["records"]:
- print(f"{record['p.name']} is {record['p.age']} years old")
-
-# Find shortest path
-path = store.shortest_path(alice["id"], bob["id"])
-print(f"Path length: {path['length']}")
-
-# Close connection
-store.close()
```
----
-
### Neo4jAdapter
-Direct Neo4j database adapter for advanced operations.
+Enterprise-grade backend.
**Features:**
-- Full Cypher query support
-- ACID transactions with rollback
-- Multi-database support
-- Index and constraint management
-- GDS (Graph Data Science) library integration
-
-**Example:**
-
-```python
-from semantica.graph_store import Neo4jAdapter
-
-adapter = Neo4jAdapter(
- uri="bolt://localhost:7687",
- user="neo4j",
- password="password",
- database="neo4j"
-)
-
-adapter.connect()
-
-# Create index for faster queries
-adapter.create_index("Person", "name", index_type="btree")
-
-# Execute complex query
-results = adapter.execute_query("""
- MATCH path = shortestPath((a:Person)-[*]-(b:Person))
- WHERE a.name = 'Alice' AND b.name = 'Bob'
- RETURN path, length(path) as distance
-""")
-
-# Get statistics
-stats = adapter.get_stats()
-print(f"Nodes: {stats['node_count']}, Relationships: {stats['relationship_count']}")
-```
-
----
+- Bolt protocol support
+- Cluster awareness
+- APOC procedure integration
### KuzuAdapter
-Embedded graph database for high-performance analytics.
+Embedded, in-process backend.
**Features:**
-- No server required (embedded)
-- Schema-based node and relationship tables
-- High-performance analytical queries
-- COPY FROM for bulk data loading
-- Persistent and in-memory modes
-
-**Example:**
-
-```python
-from semantica.graph_store import KuzuAdapter
-
-adapter = KuzuAdapter(
- database_path="./my_graph_db",
- buffer_pool_size=268435456, # 256MB
- max_num_threads=4
-)
-
-adapter.connect()
-
-# Create node table with schema
-adapter.create_node_table(
- "Person",
- properties={
- "id": "SERIAL",
- "name": "STRING",
- "age": "INT64"
- },
- primary_key="id"
-)
-
-# Create relationship table
-adapter.create_rel_table(
- "KNOWS",
- from_table="Person",
- to_table="Person",
- properties={"since": "INT64"}
-)
-
-# Create nodes
-adapter.create_node("Person", {"name": "Alice", "age": 30})
-
-# Bulk load from CSV
-adapter.bulk_load_nodes("Person", "people.csv", header=True)
-```
-
----
+- No external server required
+- Columnar storage for speed
+- Zero-copy integration with Arrow
### FalkorDBAdapter
-Ultra-fast Redis-based graph database for real-time applications.
+High-performance Redis module.
**Features:**
- Sparse matrix representation
-- Linear algebra query optimization
-- Multi-tenant graph support
-- OpenCypher query language
-- Redis-based persistence
-
-**Example:**
-
-```python
-from semantica.graph_store import FalkorDBAdapter
-
-adapter = FalkorDBAdapter(
- host="localhost",
- port=6379,
- graph_name="knowledge_graph"
-)
-
-adapter.connect()
-
-# Select/create a graph
-adapter.select_graph("MotoGP")
-
-# Create nodes and relationships
-rider = adapter.create_node(
- labels=["Rider"],
- properties={"name": "Valentino Rossi"}
-)
-
-team = adapter.create_node(
- labels=["Team"],
- properties={"name": "Yamaha"}
-)
-
-adapter.create_relationship(
- rider["id"],
- team["id"],
- "rides",
- properties={"since": 2004}
-)
-
-# Query
-results = adapter.execute_query("""
- MATCH (r:Rider)-[:rides]->(t:Team)
- WHERE t.name = 'Yamaha'
- RETURN r.name
-""")
-
-# List all graphs
-graphs = adapter.list_graphs()
-```
+- Ultra-low latency
+- Redis protocol
---
## Convenience Functions
-Quick access to graph operations without managing store instances:
-
```python
-from semantica.graph_store import (
- # Node operations
- create_node,
- create_nodes,
- get_nodes,
- update_node,
- delete_node,
-
- # Relationship operations
- create_relationship,
- create_relationships,
- get_relationships,
- delete_relationship,
-
- # Query operations
- execute_query,
-
- # Analytics operations
- shortest_path,
- get_neighbors,
- run_analytics
-)
-
-# Create nodes using convenience functions
-alice = create_node(labels=["Person"], properties={"name": "Alice"})
-bob = create_node(labels=["Person"], properties={"name": "Bob"})
-
-# Create relationship
-rel = create_relationship(
- start_id=alice["id"],
- end_id=bob["id"],
- rel_type="KNOWS"
-)
+from semantica.graph_store import execute_query, create_node
-# Query
-results = execute_query("MATCH (n:Person) RETURN n.name LIMIT 10")
+# Quick query
+results = execute_query("MATCH (n) RETURN count(n) as count")
-# Analytics
-path = shortest_path(alice["id"], bob["id"], max_depth=5)
-neighbors = get_neighbors(alice["id"], depth=2)
+# Quick node creation
+create_node(["Person"], {"name": "Bob"})
```
---
@@ -365,186 +146,65 @@ neighbors = get_neighbors(alice["id"], depth=2)
### Environment Variables
```bash
-# General settings
-export GRAPH_STORE_DEFAULT_BACKEND=neo4j
-export GRAPH_STORE_BATCH_SIZE=1000
-export GRAPH_STORE_TIMEOUT=30
-
-# Neo4j settings
-export GRAPH_STORE_NEO4J_URI=bolt://localhost:7687
-export GRAPH_STORE_NEO4J_USER=neo4j
-export GRAPH_STORE_NEO4J_PASSWORD=password
-export GRAPH_STORE_NEO4J_DATABASE=neo4j
-
-# KuzuDB settings
-export GRAPH_STORE_KUZU_DATABASE_PATH=./kuzu_db
-export GRAPH_STORE_KUZU_BUFFER_POOL_SIZE=268435456
-
-# FalkorDB settings
-export GRAPH_STORE_FALKORDB_HOST=localhost
-export GRAPH_STORE_FALKORDB_PORT=6379
-export GRAPH_STORE_FALKORDB_GRAPH_NAME=default
+export GRAPH_STORE_BACKEND=neo4j
+export NEO4J_URI=bolt://localhost:7687
+export NEO4J_USER=neo4j
+export NEO4J_PASSWORD=password
```
### YAML Configuration
```yaml
-# config.yaml - Graph Store Configuration
-
graph_store:
- backend: neo4j # neo4j, kuzu, falkordb
- batch_size: 1000
- timeout: 30
+ backend: neo4j
neo4j:
uri: bolt://localhost:7687
- user: neo4j
- password: password
- database: neo4j
- encrypted: false
+ pool_size: 50
kuzu:
- database_path: ./kuzu_db
- buffer_pool_size: 268435456
- max_num_threads: 4
-
- falkordb:
- host: localhost
- port: 6379
- password: null
- graph_name: default
-```
-
----
-
-## Backend Comparison
-
-| Feature | Neo4j | KuzuDB | FalkorDB |
-|---------|-------|--------|----------|
-| **Query Language** | Cypher | Cypher | OpenCypher |
-| **Deployment** | Server/Cloud | Embedded | Server (Redis) |
-| **Schema** | Schema-optional | Schema-required | Schema-optional |
-| **Transactions** | Full ACID | ACID | ACID |
-| **Performance** | Excellent | Best for analytics | Ultra-fast |
-| **Use Case** | Enterprise | Analytics/Embedded | Real-time/LLM |
-| **Clustering** | Yes | No | Via Redis |
-| **Graph Algorithms** | GDS Library | Built-in | Built-in |
-
----
-
-## Docker Quick Start
-
-### FalkorDB
-
-```bash
-docker run -p 6379:6379 -p 3000:3000 -it --rm \
- -v ./data:/var/lib/falkordb/data \
- falkordb/falkordb
-```
-
-Then open http://localhost:3000 for the web UI.
-
-### Neo4j
-
-```bash
-docker run -p 7474:7474 -p 7687:7687 \
- -e NEO4J_AUTH=neo4j/password \
- neo4j:latest
-```
-
-Then open http://localhost:7474 for Neo4j Browser.
-
----
-
-## Performance Tips
-
-### Indexing
-
-```python
-# Create indexes for frequently queried properties
-store.create_index("Person", "name", index_type="btree")
-store.create_index("Document", "content", index_type="fulltext")
-```
-
-### Batch Operations
-
-```python
-# Use batch operations for bulk inserts
-nodes = [
- {"labels": ["Person"], "properties": {"name": f"Person_{i}"}}
- for i in range(1000)
-]
-store.create_nodes(nodes)
-```
-
-### Query Optimization
-
-```python
-# Use parameterized queries
-results = store.execute_query(
- "MATCH (p:Person) WHERE p.age > $min_age RETURN p",
- parameters={"min_age": 25}
-)
-
-# Limit results
-results = store.get_nodes(labels=["Person"], limit=100)
+ path: ./data/kuzu_db
+ buffer_pool_size: 1024 # MB
```
---
## Integration Examples
-### Knowledge Graph for RAG
+### Hybrid Search (Vector + Graph)
```python
from semantica.graph_store import GraphStore
-from semantica.embeddings import EmbeddingGenerator
-
-# Create knowledge graph
-store = GraphStore(backend="falkordb")
-store.connect()
-
-# Add entities and relationships
-doc = store.create_node(["Document"], {"title": "AI Paper", "content": "..."})
-concept = store.create_node(["Concept"], {"name": "Machine Learning"})
-store.create_relationship(doc["id"], concept["id"], "MENTIONS")
-
-# Query for retrieval
-results = store.execute_query("""
- MATCH (d:Document)-[:MENTIONS]->(c:Concept)
- WHERE c.name CONTAINS 'Learning'
- RETURN d.title, d.content
-""")
+from semantica.vector_store import VectorStore
+
+# 1. Find relevant nodes via Vector Search
+vector_store = VectorStore()
+results = vector_store.search(query_vec, k=5)
+node_ids = [r.metadata['node_id'] for r in results]
+
+# 2. Expand context via Graph Traversal
+graph_store = GraphStore()
+query = """
+MATCH (n)-[r]-(m)
+WHERE elementId(n) IN $ids
+RETURN n, r, m
+"""
+subgraph = graph_store.execute_query(query, params={"ids": node_ids})
```
-### Social Network Analysis
+---
-```python
-from semantica.graph_store import GraphStore
+## Best Practices
-store = GraphStore(backend="neo4j")
-store.connect()
-
-# Find influential users (high degree centrality)
-results = store.execute_query("""
- MATCH (u:User)-[r:FOLLOWS]-()
- WITH u, count(r) as connections
- ORDER BY connections DESC
- RETURN u.name, connections
- LIMIT 10
-""")
-
-# Find communities
-from semantica.graph_store import run_analytics
-components = run_analytics("connected_components", labels=["User"])
-```
+1. **Use Parameters**: Always use parameters in Cypher queries (`$name`) instead of string concatenation to prevent injection and improve caching.
+2. **Batch Writes**: Use `create_nodes` (plural) for bulk insertion instead of loop-inserting.
+3. **Create Indexes**: Ensure you have indexes on frequently queried properties (`id`, `name`).
+4. **Close Connections**: Use context managers (`with GraphStore() as store:`) or call `close()` to release resources.
---
## See Also
-- [Vector Store Module](vector_store.md) - Store and search vector embeddings
-- [Triple Store Module](triple_store.md) - RDF triple storage and SPARQL queries
-- [Knowledge Graph Module](kg.md) - Build and analyze knowledge graphs
-- [Visualization Module](visualization.md) - Visualize graph structures
-
+- [Knowledge Graph Module](kg.md) - Logical layer above Graph Store
+- [Triple Store Module](triple_store.md) - RDF-based alternative
+- [Visualization Module](visualization.md) - Visualizing query results
diff --git a/docs/reference/ingest.md b/docs/reference/ingest.md
index 9d6f523e..0bfedb7f 100644
--- a/docs/reference/ingest.md
+++ b/docs/reference/ingest.md
@@ -1,559 +1,201 @@
-# Ingest Module
+# Ingest
-The `ingest` module provides comprehensive data ingestion capabilities for loading data from various sources including files, web pages, feeds, databases, and real-time streams.
-
-## Overview
-
-The ingest module supports **50+ file formats** and multiple data sources:
-
-- **File Ingestion**: PDF, DOCX, XLSX, TXT, MD, JSON, CSV, and more
-- **Web Scraping**: HTML pages, sitemaps, with JavaScript rendering
-- **Feed Processing**: RSS, Atom feeds with automatic updates
-- **Database Connectivity**: SQL and NoSQL databases
-- **Stream Processing**: Real-time data streams
-- **Email Processing**: EML, MSG, MBOX, PST archives
-- **Repository Analysis**: Git repositories and code analysis
-- **MCP Server Ingestion**: Connect to your own Python/FastMCP MCP servers via URL for resource and tool-based data ingestion
-
----
-
-## Algorithms Used
-
-### File Discovery
-- **Recursive Traversal**: Depth-first search for file discovery
-- **Pattern Matching**: Glob patterns with regex support
-- **Filtering**: Extension-based and size-based filtering
-
-### Web Scraping
-- **HTML Parsing**: BeautifulSoup/lxml DOM parsing
-- **JavaScript Rendering**: Headless browser (Selenium/Playwright)
-- **Rate Limiting**: Token bucket algorithm
-- **Robots.txt**: Compliance checking
-
-### Stream Processing
-- **Batch Buffering**: Sliding window with configurable size
-- **Backpressure Handling**: Flow control mechanisms
+> **Universal data ingestion from files, web, feeds, streams, repos, emails, and databases.**
---
-## Quick Start
+## 🎯 Overview
-```python
-from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor
+<div class="grid cards" markdown>
-# Ingest local files
-file_ingestor = FileIngestor(recursive=True)
-documents = file_ingestor.ingest("documents/", formats=["pdf", "docx"])
+- :material-file-document-multiple:{ .lg .middle } **File Ingestion**
-# Ingest web content
-web_ingestor = WebIngestor(max_depth=2)
-web_docs = web_ingestor.ingest("https://example.com/articles")
+ ---
-# Ingest RSS feeds
-feed_ingestor = FeedIngestor(max_items=100)
-feed_docs = feed_ingestor.ingest("https://example.com/rss")
+ Local and Cloud (S3/GCS/Azure) file processing with type detection
-print(f"Total documents: {len(documents) + len(web_docs) + len(feed_docs)}")
-```
+- :material-web:{ .lg .middle } **Web Crawling**
----
+ ---
-## Main Classes
-
-### FileIngestor
+ Scrape websites with rate limiting, robots.txt compliance, and JS rendering
+- :material-rss:{ .lg .middle } **Feed Monitoring**
-**Supported Formats:**
+ ---
-| Category | Formats |
-|----------|---------|
-| **Documents** | PDF, DOCX, XLSX, PPTX, TXT, RTF, ODT, EPUB, LaTeX, Markdown |
-| **Structured** | JSON, YAML, TOML, CSV, TSV, Parquet, Avro, ORC |
-| **Web** | HTML, XHTML, XML, JSON-LD, RDFa |
-| **Archives** | ZIP, TAR, RAR, 7Z, GZ, BZ2 |
-| **Scientific** | BibTeX, EndNote, RIS, JATS XML |
-| **Email** | EML, MSG, MBOX, PST |
+ Consume RSS/Atom feeds with real-time update monitoring
-**Example Usage:**
+- :material-broadcast:{ .lg .middle } **Stream Processing**
-```python
-from semantica.ingest import FileIngestor
-
-# Basic usage
-ingestor = FileIngestor()
-docs = ingestor.ingest("documents/")
-
-# Advanced configuration
-ingestor = FileIngestor(
- recursive=True,
- max_file_size=100 * 1024 * 1024, # 100MB
- supported_formats=["pdf", "docx", "xlsx"],
- extract_archives=True,
- ocr_enabled=True,
- ocr_language="eng"
-)
+ ---
-# Ingest with filters
-docs = ingestor.ingest(
- "documents/",
- formats=["pdf", "docx"],
- exclude_patterns=["*draft*", "*temp*"],
- metadata={"source": "company_docs", "version": "1.0"}
-)
+ Ingest from Kafka, RabbitMQ, Kinesis, and Pulsar
-# Process results
-for doc in docs:
- print(f"File: {doc.filename}")
- print(f"Format: {doc.format}")
- print(f"Size: {doc.size} bytes")
- print(f"Pages: {doc.metadata.get('pages', 'N/A')}")
-```
+- :material-source-branch:{ .lg .middle } **Code Repos**
----
+ ---
-### WebIngestor
+ Clone and analyze Git repositories (GitHub/GitLab)
+- :material-database:{ .lg .middle } **Databases**
-**Example Usage:**
+ ---
-```python
-from semantica.ingest import WebIngestor
-
-# Basic web scraping
-ingestor = WebIngestor()
-docs = ingestor.ingest("https://example.com")
-
-# Advanced configuration
-ingestor = WebIngestor(
- max_depth=3,
- respect_robots_txt=True,
- delay_between_requests=1.0,
- user_agent="Semantica/1.0",
- render_javascript=True,
- timeout=30
-)
+ Ingest tables and query results from SQL databases
-# Scrape with patterns
-docs = ingestor.ingest(
- "https://blog.example.com",
- patterns=["*.html", "*/articles/*"],
- exclude_patterns=["*/admin/*", "*/login/*"],
- follow_links=True,
- max_pages=100
-)
+</div>
-# Extract metadata
-for doc in docs:
- print(f"URL: {doc.url}")
- print(f"Title: {doc.metadata.get('title')}")
- print(f"Author: {doc.metadata.get('author')}")
- print(f"Published: {doc.metadata.get('published_date')}")
-```
+!!! tip "When to Use"
+ - **Data Onboarding**: The entry point for all external data into Semantica
+ - **Crawling**: Building a dataset from the web
+ - **Monitoring**: Listening to real-time data streams
+ - **Migration**: Importing legacy data from databases
---
-### FeedIngestor
-
+## ⚙️ Algorithms Used
-**Example Usage:**
+### File Processing
+- **Magic Number Detection**: Identifying file types by binary signatures, not just extensions.
+- **Recursive Traversal**: Efficiently walking directory trees.
-```python
-from semantica.ingest import FeedIngestor
-
-# Basic feed ingestion
-ingestor = FeedIngestor()
-docs = ingestor.ingest("https://example.com/rss")
-
-# Advanced configuration
-ingestor = FeedIngestor(
- max_items=1000,
- update_interval=3600, # 1 hour
- include_content=True,
- fetch_full_content=True
-)
+### Web Ingestion
+- **Sitemap Parsing**: Discovering URLs via XML sitemaps.
+- **DOM Extraction**: Removing boilerplate (nav/ads) to extract main content.
+- **Politeness**: Respecting `robots.txt` and enforcing crawl delays.
-# Ingest multiple feeds
-feeds = [
- "https://news.ycombinator.com/rss",
- "https://example.com/atom",
- "https://blog.example.com/feed"
-]
-
-all_docs = []
-for feed_url in feeds:
- docs = ingestor.ingest(feed_url)
- all_docs.extend(docs)
+### Stream Processing
+- **Consumer Groups**: Managing offsets and scaling consumption (Kafka).
+- **Backpressure**: Handling high-velocity streams without crashing.
-print(f"Total feed items: {len(all_docs)}")
-```
+### Repository Analysis
+- **AST Parsing**: Extracting code structure (classes/functions) without executing.
+- **Dependency Parsing**: Reading `requirements.txt`, `package.json`, etc.
---
-### DBIngestor
+## Main Classes
+### FileIngestor
-**Example Usage:**
+Handles file systems and object storage.
-```python
-from semantica.ingest import DBIngestor
+**Methods:**
-# SQL database ingestion
-ingestor = DBIngestor(
- connection_string="postgresql://user:pass@localhost/db"
-)
+| Method | Description |
+|--------|-------------|
+| `ingest_file(path)` | Process single file |
+| `ingest_directory(path)` | Process folder |
-docs = ingestor.ingest(
- query="SELECT title, content, author, created_at FROM articles WHERE published = true",
- metadata={"source": "articles_db", "version": "1.0"}
-)
+### WebIngestor
-# NoSQL database ingestion
-mongo_ingestor = DBIngestor(
- connection_string="mongodb://localhost:27017/mydb"
-)
+Handles web content.
-docs = mongo_ingestor.ingest(
- collection="articles",
- query={"status": "published"},
- projection={"title": 1, "content": 1, "author": 1}
-)
-```
+**Methods:**
----
+| Method | Description |
+|--------|-------------|
+| `ingest_url(url)` | Scrape page |
+| `crawl(url, depth)` | Recursive crawl |
### StreamIngestor
+Handles real-time data.
-**Example Usage:**
-
-```python
-from semantica.ingest import StreamIngestor
-
-# Kafka stream ingestion
-ingestor = StreamIngestor(
- stream_type="kafka",
- bootstrap_servers=["localhost:9092"],
- topic="documents",
- group_id="semantica-consumer"
-)
-
-# Process stream
-for doc in ingestor.stream():
- print(f"Received: {doc.id}")
- # Process document
-
-# RabbitMQ stream ingestion
-rabbitmq_ingestor = StreamIngestor(
- stream_type="rabbitmq",
- host="localhost",
- queue="documents"
-)
-```
-
----
-
-### EmailIngestor
-
-
-**Example Usage:**
-
-```python
-from semantica.ingest import EmailIngestor
-
-# Ingest email files
-ingestor = EmailIngestor()
-docs = ingestor.ingest("emails/", formats=["eml", "msg"])
-
-# Extract attachments
-ingestor = EmailIngestor(
- extract_attachments=True,
- attachment_dir="attachments/"
-)
-
-docs = ingestor.ingest("archive.mbox")
+**Methods:**
-# Process emails
-for doc in docs:
- print(f"From: {doc.metadata['from']}")
- print(f"Subject: {doc.metadata['subject']}")
- print(f"Date: {doc.metadata['date']}")
- print(f"Attachments: {len(doc.metadata.get('attachments', []))}")
-```
-
----
+| Method | Description |
+|--------|-------------|
+| `consume(topic)` | Start consumption |
### RepoIngestor
+Handles code repositories.
-**Example Usage:**
-
-```python
-from semantica.ingest import RepoIngestor
-
-# Ingest Git repository
-ingestor = RepoIngestor()
-docs = ingestor.ingest(
- "https://github.com/user/repo.git",
- branch="main",
- include_history=True
-)
-
-# Analyze code
-ingestor = RepoIngestor(
- analyze_code=True,
- extract_functions=True,
- extract_classes=True,
- languages=["python", "javascript"]
-)
+**Methods:**
-docs = ingestor.ingest("path/to/local/repo")
-```
+| Method | Description |
+|--------|-------------|
+| `ingest_repo(url)` | Clone and process |
---
-### MCPIngestor
-
-**Bring Your Own MCP Server**: The MCP (Model Context Protocol) ingestion allows you to connect to your own Python-based or FastMCP MCP servers via URL. You can bring any MCP server you've built or have access to, and Semantica will dynamically discover and ingest data from its resources and tools.
-
-**IMPORTANT**: This implementation supports **ONLY Python-based MCP servers and FastMCP servers**. Users can bring their own Python or FastMCP MCP servers via URL connections. JavaScript, TypeScript, C#, Java, and other language implementations are **NOT supported**.
-
-**Key Features:**
-- **URL-based connection**: Connect to any Python/FastMCP MCP server via HTTP/HTTPS URL
-- **Generic implementation**: Works with any Python/FastMCP MCP server across diverse domains
-- **Dynamic discovery**: Automatically discovers available resources and tools
-- **Multiple servers**: Connect to multiple MCP servers simultaneously
-- **Resource ingestion**: Ingest data from MCP server resources
-- **Tool execution**: Execute MCP server tools and ingest their outputs
-- **Authentication support**: API keys, OAuth, and custom headers
-
-**Example Usage:**
-
-```python
-from semantica.ingest import MCPIngestor
-
-# Create ingestor
-ingestor = MCPIngestor()
-
-# Connect to your MCP server via URL (primary method)
-ingestor.connect(
- "my_server", # Server identifier
- url="http://localhost:8000/mcp" # Your MCP server URL
-)
-
-# List available resources from your server
-resources = ingestor.list_available_resources("my_server")
-print(f"Available resources: {[r.uri for r in resources]}")
-
-# List available tools from your server
-tools = ingestor.list_available_tools("my_server")
-print(f"Available tools: {[t.name for t in tools]}")
-```
-
-**Resource-Based Ingestion:**
-
-```python
-from semantica.ingest import MCPIngestor
-
-ingestor = MCPIngestor()
-ingestor.connect("file_server", url="http://localhost:8000/mcp")
-
-# Ingest specific resources
-data = ingestor.ingest_resources(
- "file_server",
- resource_uris=["resource://file/documents", "resource://file/reports"]
-)
-
-for item in data:
- print(f"Resource: {item.resource_uri}")
- print(f"Content type: {item.data_type}")
- print(f"Metadata: {item.metadata}")
-
-# Ingest all available resources
-all_data = ingestor.ingest_all_resources("file_server")
-print(f"Ingested {len(all_data)} resources")
-```
-
-**Tool-Based Ingestion:**
+## Convenience Functions
```python
-from semantica.ingest import MCPIngestor
+from semantica.ingest import ingest
-ingestor = MCPIngestor()
-ingestor.connect("db_server", url="http://localhost:8000/mcp")
-
-# Execute a tool and ingest its output
-result = ingestor.ingest_tool_output(
- "db_server",
- tool_name="query_database",
- arguments={"query": "SELECT * FROM users LIMIT 10"}
-)
-
-print(f"Tool result: {result.content}")
-print(f"Metadata: {result.metadata}")
+# Auto-detect source type
+ingest("doc.pdf", source_type="file")
+ingest("https://google.com", source_type="web")
+ingest("kafka://topic", source_type="stream")
```
-**Multiple MCP Servers:**
-
-```python
-from semantica.ingest import MCPIngestor
-
-ingestor = MCPIngestor()
+---
-# Connect to multiple MCP servers simultaneously
-ingestor.connect("db_server", url="http://localhost:8001/mcp")
-ingestor.connect("file_server", url="http://localhost:8002/mcp")
-ingestor.connect(
- "api_server",
- url="https://api.example.com/mcp",
- headers={"Authorization": "Bearer your_token"}
-)
+## Configuration
-# Ingest from different servers
-db_data = ingestor.ingest_resources("db_server", resource_uris=["resource://database/tables"])
-file_data = ingestor.ingest_all_resources("file_server")
-api_result = ingestor.ingest_tool_output("api_server", tool_name="fetch_data", arguments={})
+### Environment Variables
-# List all connected servers
-servers = ingestor.get_connected_servers()
-print(f"Connected servers: {servers}")
+```bash
+export INGEST_USER_AGENT="SemanticaBot/1.0"
+export AWS_ACCESS_KEY_ID=...
+export KAFKA_BOOTSTRAP_SERVERS=localhost:9092
```
-**Authentication and HTTPS:**
+### YAML Configuration
-```python
-from semantica.ingest import MCPIngestor
-
-ingestor = MCPIngestor()
-
-# Connect via HTTPS with authentication (transport auto-detected from URL)
-ingestor.connect(
- "secure_server",
- url="https://api.example.com/mcp",
- headers={
- "Authorization": "Bearer your_api_token",
- "X-API-Key": "your_api_key"
- }
-)
-
-# The client automatically handles HTTPS and authentication headers
-resources = ingestor.list_available_resources("secure_server")
+```yaml
+ingest:
+ web:
+ user_agent: "MyBot"
+ rate_limit: 1.0 # seconds
+
+ files:
+ max_size: 100MB
+ allowed_extensions: [.pdf, .txt, .md]
```
-**Use Cases:**
-
-- **Database Integration**: Connect to a database MCP server to ingest table schemas, query results, or metadata
-- **File System Access**: Connect to a file system MCP server to ingest documents, logs, or configuration files
-- **API Integration**: Connect to an API MCP server to ingest data from external services
-- **Custom Data Sources**: Bring your own MCP server to expose any data source through the MCP protocol
-
-**Best Practices:**
-
-1. **Server Naming**: Use descriptive names for your MCP servers to easily identify them
-2. **Connection Management**: Reuse the same MCPIngestor instance for multiple servers
-3. **Error Handling**: Always handle connection errors and check server availability
-4. **Resource Discovery**: List available resources and tools before ingestion to understand server capabilities
-5. **Authentication**: Store credentials securely and use environment variables for sensitive data
-
---
-## Common Patterns
-
-### Pattern 1: Multi-Source Ingestion
-
-```python
-from semantica.ingest import FileIngestor, WebIngestor, FeedIngestor
-
-sources = []
-
-# Ingest files
-file_ingestor = FileIngestor(recursive=True)
-sources.extend(file_ingestor.ingest("documents/"))
-
-# Ingest web
-web_ingestor = WebIngestor()
-sources.extend(web_ingestor.ingest("https://example.com"))
-
-# Ingest feeds
-feed_ingestor = FeedIngestor()
-sources.extend(feed_ingestor.ingest("https://example.com/rss"))
-
-print(f"Total sources: {len(sources)}")
-```
-
-### Pattern 2: Batch Processing with Progress
-
-```python
-from semantica.ingest import FileIngestor
-from tqdm import tqdm
-
-ingestor = FileIngestor()
-files = ingestor.list_files("documents/", recursive=True)
+## Integration Examples
-docs = []
-for file_path in tqdm(files, desc="Ingesting"):
- doc = ingestor.ingest_file(file_path)
- docs.append(doc)
-```
-
-### Pattern 3: Error Handling
+### Continuous Feed Ingestion
```python
-from semantica.ingest import FileIngestor, IngestionError
-
-ingestor = FileIngestor()
+from semantica.ingest import FeedIngestor
+from semantica.pipeline import Pipeline
-successful = []
-failed = []
+# 1. Setup Monitor
+ingestor = FeedIngestor()
+pipeline = Pipeline()
-for file_path in file_paths:
- try:
- doc = ingestor.ingest_file(file_path)
- successful.append(doc)
- except IngestionError as e:
- print(f"Failed to ingest {file_path}: {e}")
- failed.append((file_path, str(e)))
+def on_new_item(item):
+ # 2. Trigger Pipeline on new content
+ pipeline.run(item.content)
-print(f"Successful: {len(successful)}, Failed: {len(failed)}")
+# 3. Start Monitoring
+ingestor.monitor(
+ "https://news.ycombinator.com/rss",
+ callback=on_new_item,
+ interval=300
+)
```
---
-## Configuration
-
-```yaml
-# config.yaml - Ingest Configuration
+## Best Practices
-ingest:
- file:
- recursive: true
- max_file_size: 104857600 # 100MB
- supported_formats: [pdf, docx, xlsx, txt, md, json, csv]
- extract_archives: true
- ocr_enabled: true
- ocr_language: eng
-
- web:
- max_depth: 3
- respect_robots_txt: true
- delay_between_requests: 1.0
- render_javascript: true
- timeout: 30
- max_pages: 1000
-
- feed:
- max_items: 1000
- update_interval: 3600
- fetch_full_content: true
-
- stream:
- batch_size: 100
- max_wait_time: 5
-```
+1. **Respect Rate Limits**: When crawling, always set a polite `rate_limit` to avoid getting banned.
+2. **Filter Content**: Use `allowed_extensions` or URL patterns to avoid ingesting junk data.
+3. **Handle Failures**: Stream ingestors should have error handlers for bad messages.
+4. **Use Credentials Securely**: Never hardcode API keys; use Environment Variables.
---
## See Also
-- [Parse Module](parse.md) - Document parsing and content extraction
-- [Normalize Module](normalize.md) - Data cleaning and normalization
-- [Core Module](core.md) - Framework orchestration
+- [Parse Module](parse.md) - Processes the raw data ingested here
+- [Split Module](split.md) - Chunks the ingested content
+- [Utils Module](utils.md) - Validation helpers
diff --git a/docs/reference/kg.md b/docs/reference/kg.md
index 58dc694d..5d00970c 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,122 @@
### 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 build, analyze_graph
-# Detect communities using Louvain
-communities = detector.detect(algorithm="louvain")
+# Build
+kg = build(sources, resolve_conflicts=True)
-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/kg_qa.md b/docs/reference/kg_qa.md
new file mode 100644
index 00000000..a2a507ba
--- /dev/null
+++ b/docs/reference/kg_qa.md
@@ -0,0 +1,216 @@
+# KG QA
+
+> **Knowledge Graph Quality Assurance system for validation, metrics, and automated repair.**
+
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-check-decagram:{ .lg .middle } **Quality Metrics**
+
+ ---
+
+ Calculate Completeness, Consistency, and Accuracy scores
+
+- :material-shield-check:{ .lg .middle } **Validation Engine**
+
+ ---
+
+ Validate against schema constraints and custom rules
+
+- :material-wrench:{ .lg .middle } **Automated Fixes**
+
+ ---
+
+ Auto-repair duplicates, missing fields, and inconsistencies
+
+- :material-file-document-edit:{ .lg .middle } **Reporting**
+
+ ---
+
+ Generate detailed quality reports (JSON, HTML, YAML)
+
+- :material-relation-many-to-many:{ .lg .middle } **Consistency**
+
+ ---
+
+ Check logical, temporal, and hierarchical consistency
+
+- :material-lightbulb:{ .lg .middle } **Suggestions**
+
+ ---
+
+ Get actionable improvement suggestions
+
+</div>
+
+!!! tip "When to Use"
+ - **Pre-Deployment**: Validate graph quality before production use
+ - **Monitoring**: Continuous quality monitoring of live graphs
+ - **Debugging**: Identify and fix issues in problematic graphs
+
+---
+
+## ⚙️ Algorithms Used
+
+### Quality Metrics
+- **Weighted Averaging**: `Score = w1*Completeness + w2*Consistency`
+- **Normalization**: Min-max scaling of scores to `0.0 - 1.0`
+- **Completeness Ratio**: `PresentProperties / RequiredProperties`
+
+### Consistency Checking
+- **Logical Consistency**: Contradiction detection (e.g., A > B and B > A)
+- **Temporal Consistency**: Time range validation (Start < End)
+- **Hierarchical Consistency**: Cycle detection in taxonomy (DFS)
+- **Domain/Range**: Type compatibility checking for relationships
+
+### Automated Fixes
+- **Duplicate Merging**: Using Deduplication module strategies
+- **Conflict Resolution**: Using Conflicts module strategies
+- **Default Injection**: Filling missing required fields with defaults
+- **Inference**: Inferring missing types or links based on topology
+
+---
+
+## Main Classes
+
+### KGQualityAssessor
+
+Coordinator for overall quality assessment.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `assess_quality(kg)` | Calculate all metrics |
+| `generate_report(kg)` | Create full report |
+
+**Example:**
+
+```python
+from semantica.kg_qa import KGQualityAssessor
+
+assessor = KGQualityAssessor()
+score = assessor.assess_overall_quality(kg)
+print(f"Graph Quality Score: {score}")
+```
+
+### ConsistencyChecker
+
+Validates graph consistency.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `check_logical(kg)` | Logical rules | Rule Engine |
+| `check_temporal(kg)` | Time validity | Range Check |
+| `check_hierarchical(kg)` | Cycles/Tree | DFS |
+
+### CompletenessValidator
+
+Checks for missing data.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `validate_entities(kg)` | Check entity fields |
+| `validate_schema(kg)` | Check schema compliance |
+
+### AutomatedFixer
+
+Applies automatic repairs.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `fix_issues(kg, issues)` | Fix reported issues |
+| `merge_duplicates(kg)` | Fix duplicates |
+| `resolve_conflicts(kg)` | Fix conflicts |
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.kg_qa import assess_quality, generate_quality_report, fix_issues
+
+# 1. Assess
+score = assess_quality(kg)
+
+# 2. Report
+report = generate_quality_report(kg, schema=my_schema)
+
+# 3. Fix
+fixed_kg = fix_issues(kg, report.issues)
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+export KG_QA_MIN_SCORE=0.7
+export KG_QA_STRICT_MODE=true
+```
+
+### YAML Configuration
+
+```yaml
+kg_qa:
+ thresholds:
+ overall: 0.7
+ completeness: 0.8
+ consistency: 0.9
+
+ weights:
+ completeness: 0.6
+ consistency: 0.4
+
+ auto_fix:
+ enabled: true
+ strategies:
+ duplicates: merge
+ missing_fields: default
+```
+
+---
+
+## Integration Examples
+
+### CI/CD Pipeline
+
+```python
+from semantica.kg_qa import assess_quality
+
+def validate_graph_deployment(kg):
+ score = assess_quality(kg)
+
+ if score < 0.8:
+ raise ValueError(f"Quality score {score} too low for deployment!")
+
+ print("Graph passed quality checks.")
+```
+
+---
+
+## Best Practices
+
+1. **Define Schema**: QA is most effective when validated against a strict schema (Ontology).
+2. **Run Regularly**: Graph quality degrades over time; run QA jobs periodically.
+3. **Review Fixes**: Automated fixes are powerful but verify them for critical data.
+4. **Handle Warnings**: Don't ignore warnings; they often indicate creeping data quality issues.
+
+---
+
+## See Also
+
+- [Ontology Module](ontology.md) - Defining schemas for validation
+- [Deduplication Module](deduplication.md) - Used for fixing duplicates
+- [Conflicts Module](conflicts.md) - Used for resolving inconsistencies
diff --git a/docs/reference/normalize.md b/docs/reference/normalize.md
index 1a3afea0..bfef60e1 100644
--- a/docs/reference/normalize.md
+++ b/docs/reference/normalize.md
@@ -1,52 +1,96 @@
-# Normalize Module
+# Normalize
-The `normalize` module provides data cleaning, normalization, and standardization capabilities to prepare text and data for semantic processing.
+> **Clean, standardize, and prepare text and data for semantic processing with comprehensive normalization capabilities.**
-## Overview
+---
-- **Text Cleaning**: Remove noise, fix encoding, standardize whitespace
-- **Entity Normalization**: Standardize entity names and formats
-- **Date Normalization**: Parse and standardize date formats
-- **Number Normalization**: Standardize numeric values and units
-- **Language Detection**: Identify document language
-- **Encoding Handling**: Fix character encoding issues
+## 🎯 Overview
----
+<div class="grid cards" markdown>
-## Algorithms Used
+- :material-text-box-remove:{ .lg .middle } **Text Cleaning**
-### Text Normalization
-- **Unicode Normalization**: NFC, NFD, NFKC, NFKD forms
-- **Whitespace Normalization**: Regex-based cleanup
-- **Case Folding**: Locale-aware case normalization
-- **Diacritic Removal**: Unicode decomposition
+ ---
-### Entity Normalization
-- **Fuzzy Matching**: Levenshtein distance < threshold
-- **Phonetic Matching**: Soundex, Metaphone algorithms
-- **Abbreviation Expansion**: Dictionary-based expansion
+ Remove noise, fix encoding issues, and standardize whitespace for clean text
-### Date/Time Normalization
-- **Parsing**: dateutil parser with multiple format support
-- **Timezone Handling**: pytz for timezone conversion
-- **Standardization**: ISO 8601 format output
+- :material-format-text:{ .lg .middle } **Entity Normalization**
----
+ ---
-## Quick Start
+ Standardize entity names, abbreviations, and formats across documents
-```python
-from semantica.normalize import TextNormalizer
+- :material-calendar-clock:{ .lg .middle } **Date & Time**
-# Initialize normalizer
-normalizer = TextNormalizer()
+ ---
-# Normalize text
-normalized_text = normalizer.normalize(raw_text)
+ Parse and standardize date/time formats to ISO 8601
-# Normalize documents
-normalized_docs = normalizer.normalize_documents(documents)
-```
+- :material-numeric:{ .lg .middle } **Number Normalization**
+
+ ---
+
+ Standardize numeric values, units, and measurements
+
+- :material-translate:{ .lg .middle } **Language Detection**
+
+ ---
+
+ Automatically detect document language with confidence scoring
+
+- :material-file-code:{ .lg .middle } **Encoding Handling**
+
+ ---
+
+ Fix character encoding issues and ensure UTF-8 compliance
+
+</div>
+
+!!! tip "Why Normalize?"
+ Normalization is crucial for:
+
+ - **Consistency**: Ensure uniform data representation
+ - **Accuracy**: Improve entity extraction and matching
+ - **Quality**: Reduce noise and errors in downstream processing
+ - **Performance**: Enable better deduplication and search
+
+---
+
+## ⚙️ Algorithms Used
+
+### Text Normalization
+- **Unicode Normalization**: NFC, NFD, NFKC, NFKD forms using Unicode standard
+- **Whitespace Normalization**: Regex-based cleanup (`\s+` → single space)
+- **Case Folding**: Locale-aware case normalization (Unicode case folding)
+- **Diacritic Removal**: Unicode decomposition and combining character removal
+- **Punctuation Handling**: Smart punctuation normalization preserving sentence structure
+
+### Entity Normalization
+- **Fuzzy Matching**: Levenshtein distance with configurable threshold (default: 0.85)
+- **Phonetic Matching**: Soundex and Metaphone algorithms for name variants
+- **Abbreviation Expansion**: Dictionary-based expansion with context awareness
+- **Canonical Form Selection**: Frequency-based or confidence-based selection
+- **Entity Linking**: Hash-based entity ID generation for cross-document linking
+
+### Date/Time Normalization
+- **Parsing**: dateutil parser with 100+ format support
+- **Timezone Handling**: pytz for timezone conversion and DST handling
+- **Standardization**: ISO 8601 format output (YYYY-MM-DDTHH:MM:SSZ)
+- **Relative Date Resolution**: Convert "yesterday", "last week" to absolute dates
+- **Fuzzy Date Parsing**: Handle incomplete dates (e.g., "March 2024")
+
+### Number Normalization
+- **Numeric Parsing**: Handle various formats (1,000.00, 1.000,00, 1 000.00)
+- **Unit Conversion**: Standardize units (km → meters, lbs → kg)
+- **Scientific Notation**: Parse and normalize scientific notation
+- **Percentage Handling**: Normalize percentage representations
+- **Currency Normalization**: Standardize currency symbols and amounts
+
+### Language Detection
+- **N-gram Analysis**: Character and word n-gram frequency analysis
+- **Statistical Models**: Language-specific statistical models
+- **Confidence Scoring**: Probability-based confidence scores
+- **Multi-language Support**: 100+ languages supported
---
@@ -54,27 +98,101 @@ normalized_docs = normalizer.normalize_documents(documents)
### TextNormalizer
+Main text normalization orchestrator with comprehensive cleaning capabilities.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `normalize(text)` | Normalize single text | Full normalization pipeline |
+| `normalize_documents(docs)` | Batch normalize documents | Parallel processing |
+| `clean(text)` | Clean text only | Noise removal |
+| `fix_encoding(text)` | Fix encoding issues | Character encoding detection |
+| `normalize_whitespace(text)` | Standardize whitespace | Regex-based cleanup |
+| `remove_diacritics(text)` | Remove accents | Unicode decomposition |
+
+**Configuration Options:**
+
+```python
+TextNormalizer(
+ lowercase=False, # Convert to lowercase
+ remove_punctuation=False, # Remove all punctuation
+ remove_numbers=False, # Remove numeric values
+ remove_whitespace=True, # Normalize whitespace
+ fix_encoding=True, # Fix encoding issues
+ remove_diacritics=False, # Remove accents/diacritics
+ normalize_unicode=True, # Unicode normalization (NFC)
+ remove_urls=False, # Remove URLs
+ remove_emails=False, # Remove email addresses
+ remove_phone_numbers=False, # Remove phone numbers
+ expand_contractions=False, # Expand contractions (don't → do not)
+ remove_html=True, # Remove HTML tags
+ remove_extra_spaces=True, # Remove extra spaces
+ strip=True # Strip leading/trailing whitespace
+)
+```
**Example:**
```python
from semantica.normalize import TextNormalizer
+# Basic normalization
normalizer = TextNormalizer(
lowercase=False,
remove_punctuation=False,
- remove_numbers=False,
- remove_whitespace=True,
- fix_encoding=True
+ fix_encoding=True,
+ normalize_whitespace=True
)
text = " Apple Inc. was founded in 1976. "
normalized = normalizer.normalize(text)
+print(normalized)
# Output: "Apple Inc. was founded in 1976."
+
+# Aggressive cleaning
+aggressive_normalizer = TextNormalizer(
+ lowercase=True,
+ remove_punctuation=True,
+ remove_numbers=True,
+ remove_urls=True,
+ expand_contractions=True
+)
+
+text = "Check out https://example.com! It's amazing (founded in 2020)."
+cleaned = aggressive_normalizer.normalize(text)
+print(cleaned)
+# Output: "check out it is amazing founded in"
```
+---
+
### EntityNormalizer
+Standardize entity names and resolve variations to canonical forms.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `normalize(entities)` | Normalize entity list | Fuzzy + phonetic matching |
+| `normalize_single(entity)` | Normalize one entity | Canonical form lookup |
+| `add_canonical(entity, canonical)` | Add canonical mapping | Dictionary update |
+| `get_canonical(entity)` | Get canonical form | Fuzzy search |
+
+**Configuration Options:**
+
+```python
+EntityNormalizer(
+ fuzzy_matching=True, # Enable fuzzy matching
+ similarity_threshold=0.85, # Similarity threshold (0-1)
+ phonetic_matching=False, # Enable phonetic matching
+ case_sensitive=False, # Case-sensitive matching
+ preserve_case=True, # Preserve original case in output
+ expand_abbreviations=True, # Expand common abbreviations
+ canonical_dict=None # Custom canonical mappings
+)
+```
**Example:**
@@ -83,33 +201,486 @@ from semantica.normalize import EntityNormalizer
normalizer = EntityNormalizer(
fuzzy_matching=True,
- similarity_threshold=0.85
+ similarity_threshold=0.85,
+ expand_abbreviations=True
)
-# Normalize entity names
-entities = ["Apple Inc.", "Apple", "AAPL", "Apple Computer"]
+# Normalize entity variations
+entities = [
+ "Apple Inc.",
+ "Apple",
+ "AAPL",
+ "Apple Computer",
+ "Apple, Inc."
+]
+
normalized = normalizer.normalize(entities)
+print(normalized)
# All mapped to canonical form: "Apple Inc."
+
+# Add custom canonical mappings
+normalizer.add_canonical("AAPL", "Apple Inc.")
+normalizer.add_canonical("Microsoft Corp", "Microsoft Corporation")
+
+# Get canonical form
+canonical = normalizer.get_canonical("MSFT")
+print(canonical) # "Microsoft Corporation"
```
+---
+
### DateNormalizer
+Parse and standardize date/time formats to ISO 8601.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `normalize(date_string)` | Parse and normalize date | dateutil parser |
+| `normalize_batch(dates)` | Batch normalize dates | Parallel processing |
+| `parse_relative(relative_date)` | Parse relative dates | Date arithmetic |
+| `detect_format(date_string)` | Detect date format | Pattern matching |
+
+**Configuration Options:**
+
+```python
+DateNormalizer(
+ output_format="ISO8601", # ISO8601, UNIX, custom format
+ timezone="UTC", # Target timezone
+ handle_relative=True, # Parse "yesterday", "last week"
+ fuzzy=True, # Fuzzy parsing
+ default_day=1, # Default day for incomplete dates
+ default_month=1 # Default month for incomplete dates
+)
+```
**Example:**
```python
from semantica.normalize import DateNormalizer
-normalizer = DateNormalizer(output_format="ISO8601")
+normalizer = DateNormalizer(
+ output_format="ISO8601",
+ timezone="UTC",
+ handle_relative=True
+)
+
+# Normalize various date formats
+dates = [
+ "Jan 1, 2024",
+ "01/01/2024",
+ "2024-01-01",
+ "1st January 2024",
+ "yesterday",
+ "March 2024"
+]
-dates = ["Jan 1, 2024", "01/01/2024", "2024-01-01"]
normalized = [normalizer.normalize(d) for d in dates]
-# All output: "2024-01-01T00:00:00Z"
+for original, norm in zip(dates, normalized):
+ print(f"{original:20} → {norm}")
+
+# Output:
+# Jan 1, 2024 → 2024-01-01T00:00:00Z
+# 01/01/2024 → 2024-01-01T00:00:00Z
+# 2024-01-01 → 2024-01-01T00:00:00Z
+# 1st January 2024 → 2024-01-01T00:00:00Z
+# yesterday → 2024-11-29T00:00:00Z
+# March 2024 → 2024-03-01T00:00:00Z
+
+# Custom format
+custom_normalizer = DateNormalizer(output_format="%Y/%m/%d")
+result = custom_normalizer.normalize("Jan 1, 2024")
+print(result) # "2024/01/01"
+```
+
+---
+
+### NumberNormalizer
+
+Standardize numeric values, units, and measurements.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `normalize(number_string)` | Parse and normalize number | Regex parsing |
+| `convert_units(value, from_unit, to_unit)` | Convert units | Unit conversion |
+| `parse_currency(currency_string)` | Parse currency | Currency parsing |
+| `normalize_percentage(percent_string)` | Normalize percentage | Percentage parsing |
+
+**Example:**
+
+```python
+from semantica.normalize import NumberNormalizer
+
+normalizer = NumberNormalizer(
+ decimal_separator=".",
+ thousands_separator=",",
+ normalize_units=True
+)
+
+# Normalize various number formats
+numbers = [
+ "1,000.50",
+ "1.000,50",
+ "1 000.50",
+ "$1,234.56",
+ "50%",
+ "1.5e3"
+]
+
+normalized = [normalizer.normalize(n) for n in numbers]
+for original, norm in zip(numbers, normalized):
+ print(f"{original:15} → {norm}")
+
+# Unit conversion
+distance_km = normalizer.convert_units(5, "km", "m")
+print(f"5 km = {distance_km} m") # 5000 m
+```
+
+---
+
+### LanguageDetector
+
+Detect document language with confidence scoring.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `detect(text)` | Detect language | N-gram analysis |
+| `detect_batch(texts)` | Batch detect languages | Parallel processing |
+| `get_confidence(text, language)` | Get confidence score | Statistical model |
+
+**Example:**
+
+```python
+from semantica.normalize import LanguageDetector
+
+detector = LanguageDetector()
+
+# Detect language
+texts = [
+ "Hello, how are you?",
+ "Bonjour, comment allez-vous?",
+ "Hola, ¿cómo estás?",
+ "Hallo, wie geht es dir?",
+ "こんにちは、お元気ですか?"
+]
+
+for text in texts:
+ result = detector.detect(text)
+ print(f"{text[:30]:30} → {result['language']} ({result['confidence']:.2f})")
+
+# Output:
+# Hello, how are you? → en (0.99)
+# Bonjour, comment allez-vous? → fr (0.98)
+# Hola, ¿cómo estás? → es (0.97)
+# Hallo, wie geht es dir? → de (0.96)
+# こんにちは、お元気ですか? → ja (0.99)
+```
+
+---
+
+## Convenience Functions
+
+Quick access to normalization operations:
+
+```python
+from semantica.normalize import (
+ normalize_text,
+ normalize_entities,
+ normalize_dates,
+ normalize_numbers,
+ detect_language,
+ fix_encoding
+)
+
+# Normalize text
+clean_text = normalize_text(" Messy text ", remove_extra_spaces=True)
+
+# Normalize entities
+canonical_entities = normalize_entities(["Apple Inc.", "Apple", "AAPL"])
+
+# Normalize dates
+iso_dates = normalize_dates(["Jan 1, 2024", "01/01/2024"])
+
+# Normalize numbers
+standard_numbers = normalize_numbers(["1,000.50", "$1,234.56"])
+
+# Detect language
+language = detect_language("Hello, world!")
+
+# Fix encoding
+fixed_text = fix_encoding("Caf\u00e9") # Café
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+# Normalization settings
+export NORMALIZE_DEFAULT_LOWERCASE=false
+export NORMALIZE_DEFAULT_ENCODING=utf-8
+export NORMALIZE_DEFAULT_TIMEZONE=UTC
+
+# Entity normalization
+export NORMALIZE_ENTITY_SIMILARITY_THRESHOLD=0.85
+export NORMALIZE_ENTITY_FUZZY_MATCHING=true
+
+# Language detection
+export NORMALIZE_LANGUAGE_DETECTOR=langdetect
+export NORMALIZE_LANGUAGE_CONFIDENCE_THRESHOLD=0.8
+```
+
+### YAML Configuration
+
+```yaml
+# config.yaml - Normalize Module Configuration
+
+normalize:
+ text:
+ lowercase: false
+ remove_punctuation: false
+ fix_encoding: true
+ normalize_whitespace: true
+ remove_urls: false
+ expand_contractions: false
+
+ entity:
+ fuzzy_matching: true
+ similarity_threshold: 0.85
+ phonetic_matching: false
+ expand_abbreviations: true
+
+ date:
+ output_format: "ISO8601"
+ timezone: "UTC"
+ handle_relative: true
+ fuzzy: true
+
+ number:
+ decimal_separator: "."
+ thousands_separator: ","
+ normalize_units: true
+
+ language:
+ detector: "langdetect" # langdetect, fasttext
+ confidence_threshold: 0.8
+ fallback_language: "en"
+```
+
+---
+
+## Integration Examples
+
+### Complete Document Normalization Pipeline
+
+```python
+from semantica.normalize import TextNormalizer, EntityNormalizer, DateNormalizer, LanguageDetector
+from semantica.parse import DocumentParser
+
+# Parse documents
+parser = DocumentParser()
+documents = parser.parse(["document1.pdf", "document2.docx"])
+
+# Detect language
+detector = LanguageDetector()
+for doc in documents:
+ lang_result = detector.detect(doc.content)
+ doc.metadata["language"] = lang_result["language"]
+ doc.metadata["language_confidence"] = lang_result["confidence"]
+
+# Normalize text
+text_normalizer = TextNormalizer(
+ fix_encoding=True,
+ normalize_whitespace=True,
+ remove_html=True
+)
+
+for doc in documents:
+ doc.content = text_normalizer.normalize(doc.content)
+
+# Normalize dates in metadata
+date_normalizer = DateNormalizer(output_format="ISO8601")
+for doc in documents:
+ if "date" in doc.metadata:
+ doc.metadata["date"] = date_normalizer.normalize(doc.metadata["date"])
+
+# Normalize entities
+entity_normalizer = EntityNormalizer(similarity_threshold=0.85)
+# ... entity normalization logic
+```
+
+### Multi-Language Document Processing
+
+```python
+from semantica.normalize import LanguageDetector, TextNormalizer
+
+detector = LanguageDetector()
+normalizers = {
+ "en": TextNormalizer(expand_contractions=True),
+ "fr": TextNormalizer(remove_diacritics=False),
+ "de": TextNormalizer(lowercase=False)
+}
+
+def process_multilingual_document(text):
+ # Detect language
+ lang_result = detector.detect(text)
+ language = lang_result["language"]
+
+ # Use language-specific normalizer
+ normalizer = normalizers.get(language, TextNormalizer())
+ normalized = normalizer.normalize(text)
+
+ return {
+ "text": normalized,
+ "language": language,
+ "confidence": lang_result["confidence"]
+ }
+
+# Process documents
+documents = ["Hello world", "Bonjour le monde", "Hallo Welt"]
+results = [process_multilingual_document(doc) for doc in documents]
+```
+
+---
+
+## Best Practices
+
+### 1. Choose Appropriate Normalization Level
+
+```python
+# Minimal normalization for entity extraction
+minimal = TextNormalizer(
+ fix_encoding=True,
+ normalize_whitespace=True
+)
+
+# Moderate normalization for search
+moderate = TextNormalizer(
+ fix_encoding=True,
+ normalize_whitespace=True,
+ lowercase=True,
+ remove_urls=True
+)
+
+# Aggressive normalization for topic modeling
+aggressive = TextNormalizer(
+ lowercase=True,
+ remove_punctuation=True,
+ remove_numbers=True,
+ remove_urls=True,
+ expand_contractions=True
+)
+```
+
+### 2. Preserve Original Data
+
+```python
+# Always keep original text
+doc.original_content = doc.content
+doc.content = normalizer.normalize(doc.content)
+
+# Store normalization metadata
+doc.metadata["normalized"] = True
+doc.metadata["normalization_config"] = normalizer.config
+```
+
+### 3. Batch Processing for Performance
+
+```python
+# Batch normalize for better performance
+texts = [doc.content for doc in documents]
+normalized_texts = normalizer.normalize_documents(texts)
+
+for doc, normalized in zip(documents, normalized_texts):
+ doc.content = normalized
+```
+
+---
+
+## Troubleshooting
+
+### Common Issues
+
+**Issue**: Encoding errors with special characters
+
+```python
+# Solution: Enable encoding fix
+normalizer = TextNormalizer(fix_encoding=True)
+
+# Or manually fix encoding
+from semantica.normalize import fix_encoding
+fixed_text = fix_encoding(problematic_text)
+```
+
+**Issue**: Over-normalization losing important information
+
+```python
+# Solution: Use conservative settings
+normalizer = TextNormalizer(
+ lowercase=False, # Keep case
+ remove_punctuation=False, # Keep punctuation
+ remove_numbers=False # Keep numbers
+)
+```
+
+**Issue**: Slow processing for large documents
+
+```python
+# Solution: Use batch processing
+normalizer = TextNormalizer()
+normalized = normalizer.normalize_documents(
+ documents,
+ batch_size=100,
+ n_jobs=4 # Parallel processing
+)
+```
+
+---
+
+## Performance Tips
+
+### Memory Optimization
+
+```python
+# Process documents in chunks
+def normalize_large_corpus(documents, chunk_size=1000):
+ normalizer = TextNormalizer()
+
+ for i in range(0, len(documents), chunk_size):
+ chunk = documents[i:i + chunk_size]
+ normalized_chunk = normalizer.normalize_documents(chunk)
+ yield from normalized_chunk
+```
+
+### Speed Optimization
+
+```python
+# Disable unnecessary features
+fast_normalizer = TextNormalizer(
+ fix_encoding=False, # Skip if encoding is known good
+ normalize_unicode=False, # Skip if not needed
+ remove_diacritics=False # Skip if not needed
+)
+
+# Use parallel processing
+normalizer.normalize_documents(
+ documents,
+ n_jobs=-1 # Use all CPU cores
+)
```
---
## See Also
-- [Parse Module](parse.md)
-- [Semantic Extract Module](semantic_extract.md)
+- [Parse Module](parse.md) - Document parsing and extraction
+- [Semantic Extract Module](semantic_extract.md) - Entity and relation extraction
+- [Split Module](split.md) - Text chunking and splitting
+- [Ingest Module](ingest.md) - Data ingestion
diff --git a/docs/reference/ontology.md b/docs/reference/ontology.md
index de45e1f3..0b8d25bf 100644
--- a/docs/reference/ontology.md
+++ b/docs/reference/ontology.md
@@ -1,6 +1,6 @@
-# Ontology Module
+# Ontology
-> **Generate W3C-compliant OWL ontologies from unstructured content using a 6-stage LLM pipeline.**
+> **Automated ontology generation, validation, and management system.**
---
@@ -8,98 +8,71 @@
<div class="grid cards" markdown>
-- :material-auto-fix:{ .lg .middle } **Automatic Generation**
+- :material-factory:{ .lg .middle } **Automated Generation**
---
- LLM-based ontology creation from text and knowledge graphs
+ 6-stage pipeline to generate OWL ontologies from raw data
-- :material-file-tree:{ .lg .middle } **OWL/RDF Support**
+- :material-sitemap:{ .lg .middle } **Inference Engine**
---
- W3C-compliant ontology formats with Turtle, RDF/XML, JSON-LD
+ Infer classes, properties, and hierarchies from entity patterns
-- :material-check-circle:{ .lg .middle } **Validation**
+- :material-check-decagram:{ .lg .middle } **Validation**
---
- HermiT and Pellet reasoner integration for consistency checking
+ Symbolic reasoning (HermiT/Pellet) for consistency checking
-- :material-family-tree:{ .lg .middle } **Class Hierarchy**
+- :material-recycle:{ .lg .middle } **Reuse Management**
---
- Automatic taxonomy generation with multiple inheritance
+ Import and align with standard ontologies (FOAF, Schema.org)
-- :material-link:{ .lg .middle } **Property Definition**
+- :material-chart-bar:{ .lg .middle } **Evaluation**
---
- Object and data properties with domain/range inference
+ Assess ontology quality using coverage, completeness, and granularity metrics
-- :material-brain:{ .lg .middle } **6-Stage Pipeline**
+- :material-file-code:{ .lg .middle } **OWL/RDF Export**
---
- Semantic parsing → Definitions → Types → Hierarchy → TTL → Validation
+ Export to Turtle, RDF/XML, and JSON-LD formats
</div>
-!!! info "6-Stage Ontology Generation Pipeline"
- ```mermaid
- graph LR
- A[1. Semantic Network<br/>Parsing] --> B[2. YAML to<br/>Definition]
- B --> C[3. Definition<br/>to Types]
- C --> D[4. Hierarchy<br/>Generation]
- D --> E[5. TTL<br/>Generation]
- E --> F[6. Symbolic<br/>Validation]
-
- style A fill:#e3f2fd
- style F fill:#c8e6c9
- ```
+!!! tip "When to Use"
+ - **Schema Design**: When defining the structure of your Knowledge Graph
+ - **Data Modeling**: To formalize domain concepts and relationships
+ - **Interoperability**: To ensure your data follows standard semantic web practices
+ - **Validation**: To enforce constraints on your data
---
## ⚙️ Algorithms Used
-### 6-Stage Ontology Generation Pipeline
+### 6-Stage Generation Pipeline
+1. **Semantic Network Parsing**: Extract concepts and patterns from raw entity/relationship data.
+2. **YAML-to-Definition**: Transform patterns into intermediate class definitions.
+3. **Definition-to-Types**: Map definitions to OWL types (`owl:Class`, `owl:ObjectProperty`).
+4. **Hierarchy Generation**: Build taxonomy trees using transitive closure and cycle detection.
+5. **TTL Generation**: Serialize to Turtle format using `rdflib`.
+6. **Symbolic Validation**: Run reasoner to check for logical inconsistencies.
-**Stage 1: Semantic Network Parsing**
-- Extract domain concepts from text
-- Identify key entities and relationships
-- Build initial concept graph
+### Inference Algorithms
+- **Class Inference**: Clustering entities by type and attribute similarity.
+- **Property Inference**: Determining domain/range based on connected entity types.
+- **Hierarchy Inference**: `A is_a B` detection based on subset relationships.
-**Stage 2: YAML-to-Definition**
-- Transform semantic network to class definitions
-- Define class hierarchies and properties
-- Generate human-readable descriptions
-
-**Stage 3: Definition-to-Types**
-- Map to OWL types (Class, ObjectProperty, DataProperty)
-- Define domains and ranges
-- Specify cardinality constraints
-
-**Stage 4: Hierarchy Generation**
-- Build taxonomic structures (is-a relationships)
-- Identify parent-child relationships
-- Create multiple inheritance where appropriate
-
-**Stage 5: TTL Generation**
-- Generate OWL/Turtle syntax
-- Add namespace declarations
-- Format according to W3C standards
-
-**Stage 6: Symbolic Validation**
-- HermiT/Pellet reasoning for consistency
-- Detect logical contradictions
-- Validate class satisfiability
-
-### Reasoning Algorithms
-- **HermiT**: Hypertableau reasoning algorithm
-- **Pellet**: Tableau-based DL reasoner
-- **Consistency Checking**: Detect unsatisfiable classes
-- **Classification**: Compute inferred class hierarchy
+### Validation
+- **Symbolic Reasoning**: Uses HermiT or Pellet to check satisfiability.
+- **Constraint Checking**: Validates cardinality, domain, and range constraints.
+- **Hallucination Detection**: LLM-based verification of generated concepts.
---
@@ -107,243 +80,135 @@
### OntologyGenerator
+Main entry point for the generation pipeline.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `generate(source)` | Generate ontology | 6-stage pipeline |
-| `generate_from_graph(kg)` | Generate from knowledge graph | Graph analysis + LLM generation |
-| `generate_from_text(text)` | Generate from text | Text analysis + concept extraction |
-| `validate(ontology)` | Validate ontology | Reasoner-based validation |
-| `infer_hierarchy(classes)` | Infer class hierarchy | Hierarchical clustering + LLM |
+| Method | Description |
+|--------|-------------|
+| `generate_ontology(data)` | Run full pipeline |
+| `generate_from_schema(schema)` | Generate from explicit schema |
**Example:**
```python
from semantica.ontology import OntologyGenerator
-generator = OntologyGenerator(
- llm_provider="openai",
- llm_model="gpt-4",
- validation_reasoner="hermit" # hermit, pellet
-)
-
-# Generate from knowledge graph
-ontology = generator.generate_from_graph(kg)
-
-# Validate
-is_valid, errors = generator.validate(ontology)
-print(f"Valid: {is_valid}, Errors: {len(errors)}")
-
-# Save
-ontology.save("ontology.owl", format="owl")
+generator = OntologyGenerator(base_uri="http://example.org/onto/")
+ontology = generator.generate_ontology({
+ "entities": entities,
+ "relationships": relationships
+})
+print(ontology.serialize(format="turtle"))
```
----
-
### OntologyValidator
+Validates ontology consistency.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `validate(ontology)` | Full validation | Consistency + satisfiability checks |
-| `check_consistency()` | Check logical consistency | Tableau reasoning |
-| `check_satisfiability(class_name)` | Check class satisfiability | Subsumption testing |
-| `find_inconsistencies()` | Find logical errors | Reasoner-based detection |
-| `explain_inconsistency(class_name)` | Explain why class is unsatisfiable | Axiom tracing |
-
-**Validation Checks:**
-- **Consistency**: No logical contradictions
-- **Satisfiability**: All classes can have instances
-- **Coherence**: No unsatisfiable classes
-- **Completeness**: All required axioms present
-
-**Example:**
-
-```python
-from semantica.ontology import OntologyValidator
+| Method | Description |
+|--------|-------------|
+| `validate(ontology)` | Run symbolic reasoner |
+| `check_constraints(ontology)` | Check structural rules |
-validator = OntologyValidator(reasoner="hermit")
+### OntologyEvaluator
-# Validate ontology
-result = validator.validate(ontology)
+Scores ontology quality.
-if not result.is_valid:
- print("Inconsistencies found:")
- for error in result.errors:
- print(f" - {error.class_name}: {error.message}")
- explanation = validator.explain_inconsistency(error.class_name)
- print(f" Reason: {explanation}")
-```
+**Methods:**
----
+| Method | Description |
+|--------|-------------|
+| `evaluate(ontology)` | Calculate all metrics |
+| `check_competency(questions)` | Verify coverage |
-### OWLGenerator
+### ReuseManager
+Manages external dependencies.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `generate_owl(ontology)` | Generate OWL file | OWL/XML or Turtle serialization |
-| `generate_classes(classes)` | Generate class definitions | OWL Class axioms |
-| `generate_properties(properties)` | Generate properties | ObjectProperty/DataProperty axioms |
-| `generate_individuals(individuals)` | Generate instances | Individual assertions |
-| `add_axiom(axiom)` | Add OWL axiom | Axiom insertion |
-
-**OWL Constructs:**
-- **Classes**: `owl:Class`
-- **Object Properties**: `owl:ObjectProperty`
-- **Data Properties**: `owl:DatatypeProperty`
-- **Individuals**: `owl:NamedIndividual`
-- **Restrictions**: `owl:Restriction`, `owl:someValuesFrom`, `owl:allValuesFrom`
+| Method | Description |
+|--------|-------------|
+| `import_ontology(uri)` | Load external ontology |
+| `align_concepts(source, target)` | Map equivalent classes |
-**Example:**
+---
-```python
-from semantica.ontology import OWLGenerator
+## Convenience Functions
-generator = OWLGenerator(
- base_uri="http://example.org/ontology#",
- format="turtle" # turtle, owl-xml, rdf-xml
-)
+```python
+from semantica.ontology import generate_ontology, validate_ontology
-# Generate OWL
-owl_content = generator.generate_owl(ontology)
+# Quick generation
+onto = generate_ontology(data, method="default")
-# Save
-with open("ontology.ttl", "w") as f:
- f.write(owl_content)
+# Quick validation
+is_valid, report = validate_ontology(onto)
```
---
-### PropertyGenerator
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `generate_properties(relationships)` | Generate all properties | Relationship analysis |
-| `infer_domain_range(property)` | Infer domain and range | Type inference from usage |
-| `generate_object_property(name, domain, range)` | Create object property | OWL ObjectProperty axiom |
-| `generate_data_property(name, domain, datatype)` | Create data property | OWL DatatypeProperty axiom |
-
-**Property Types:**
-- **Object Properties**: Relate individuals to individuals
-- **Data Properties**: Relate individuals to data values
-- **Annotation Properties**: Metadata properties
+## Configuration
-**Example:**
+### Environment Variables
-```python
-from semantica.ontology import PropertyGenerator
-
-generator = PropertyGenerator()
+```bash
+export ONTOLOGY_BASE_URI="http://my-org.com/ontology/"
+export ONTOLOGY_REASONER="hermit"
+export ONTOLOGY_STRICT_MODE=true
+```
-# Generate properties from relationships
-properties = generator.generate_properties(relationships)
+### YAML Configuration
-# Create specific property
-founder_property = generator.generate_object_property(
- name="foundedBy",
- domain="Organization",
- range="Person"
-)
+```yaml
+ontology:
+ base_uri: "http://example.org/"
+ generation:
+ min_class_size: 5
+ infer_hierarchy: true
+
+ validation:
+ reasoner: hermit
+ timeout: 60
```
---
-### ClassInferrer
-
-
-**Methods:**
-
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `infer_classes(entities)` | Infer class definitions | Entity type clustering |
-| `build_hierarchy(classes)` | Build class hierarchy | Hierarchical clustering + LLM |
-| `identify_disjoint_classes(classes)` | Find disjoint classes | Logical analysis |
-| `generate_restrictions(class_name)` | Generate class restrictions | Property analysis |
+## Integration Examples
-**Hierarchy Building:**
-- **Bottom-up**: Start with specific classes, generalize
-- **Top-down**: Start with general classes, specialize
-- **Hybrid**: Combine both approaches
+### Schema-First Knowledge Graph
----
+```python
+from semantica.ontology import OntologyGenerator
+from semantica.kg import KnowledgeGraph
-## Configuration
+# 1. Generate Ontology from Sample Data
+generator = OntologyGenerator()
+ontology = generator.generate_ontology(sample_data)
-```yaml
-# config.yaml - Ontology Configuration
+# 2. Initialize KG with Ontology
+kg = KnowledgeGraph(schema=ontology)
-ontology:
- generation:
- llm_provider: openai
- llm_model: gpt-4
- temperature: 0.1
- stages:
- - semantic_network_parsing
- - yaml_to_definition
- - definition_to_types
- - hierarchy_generation
- - ttl_generation
- - symbolic_validation
-
- validation:
- reasoner: hermit # hermit, pellet
- check_consistency: true
- check_satisfiability: true
- explain_errors: true
-
- owl:
- base_uri: "http://example.org/ontology#"
- format: turtle # turtle, owl-xml, rdf-xml
- include_annotations: true
- include_individuals: true
+# 3. Add Data (Validated against Ontology)
+kg.add_entities(full_dataset) # Will raise error if violates schema
```
---
-## OWL Example
-
-```turtle
-@prefix : <http://example.org/ontology#> .
-@prefix owl: <http://www.w3.org/2002/07/owl#> .
-@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
-@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
-
-# Classes
-:Person rdf:type owl:Class .
-:Organization rdf:type owl:Class .
-:Company rdf:type owl:Class ;
- rdfs:subClassOf :Organization .
-
-# Object Properties
-:foundedBy rdf:type owl:ObjectProperty ;
- rdfs:domain :Organization ;
- rdfs:range :Person .
-
-# Data Properties
-:foundedYear rdf:type owl:DatatypeProperty ;
- rdfs:domain :Organization ;
- rdfs:range xsd:gYear .
-
-# Individuals
-:AppleInc rdf:type :Company ;
- :foundedBy :SteveJobs ;
- :foundedYear "1976"^^xsd:gYear .
-```
+## Best Practices
+
+1. **Reuse Standard Ontologies**: Don't reinvent `Person` or `Organization`; import FOAF or Schema.org using `ReuseManager`.
+2. **Validate Early**: Run validation during generation to catch logical errors before populating the graph.
+3. **Use Competency Questions**: Define what questions your ontology should answer and use `OntologyEvaluator` to verify.
+4. **Version Control**: Treat ontologies like code. Use `VersionManager` to track changes.
---
## See Also
-- [Knowledge Graph Module](kg.md) - Build knowledge graphs
-- [Triple Store Module](triple_store.md) - Store RDF triples
-- [Reasoning Module](reasoning.md) - Logical reasoning
+- [Knowledge Graph Module](kg.md) - The instance data following the ontology
+- [Reasoning Module](reasoning.md) - Uses the ontology for inference
+- [Visualization Module](visualization.md) - Visualizing the class hierarchy
diff --git a/docs/reference/parse.md b/docs/reference/parse.md
index ab50298c..d2904fe7 100644
--- a/docs/reference/parse.md
+++ b/docs/reference/parse.md
@@ -1,379 +1,228 @@
-# Parse Module
+# Parse
-The `parse` module provides comprehensive document parsing capabilities for extracting content, metadata, and structure from various file formats.
-
-## Overview
-
-- **Document Parsing**: PDF, DOCX, XLSX, PPTX, and more
-- **OCR Processing**: Extract text from images and scanned documents
-- **Table Extraction**: Extract tables with structure preservation
-- **Metadata Extraction**: Author, title, dates, and custom metadata
-- **Structure Analysis**: Headings, sections, lists, and document hierarchy
-- **Multi-Format Support**: 50+ file formats with specialized parsers
+> **Universal data parser supporting documents, web content, structured data, emails, code, and media.**
---
-## Algorithms Used
+## 🎯 Overview
-### PDF Parsing
-- **Text Extraction**: PDFMiner algorithm for text layout analysis
-- **OCR**: Tesseract with preprocessing (deskewing, noise reduction)
-- **Table Detection**: Hough transform for line detection + clustering
-- **Layout Analysis**: XY-cut algorithm for reading order determination
+<div class="grid cards" markdown>
-### OCR Algorithms
-- **Preprocessing**: Otsu's thresholding, morphological operations
-- **Text Detection**: EAST/CRAFT deep learning models
-- **Recognition**: Tesseract LSTM + language models
-- **Post-processing**: Spell correction, confidence filtering
+- :material-file-document:{ .lg .middle } **Document Parsing**
-### Table Extraction
-- **Rule-based**: Line detection + cell clustering
-- **ML-based**: Deep learning table structure recognition
-- **Hybrid**: Combine rules + ML for robustness
+ ---
----
+ Extract text, tables, and metadata from PDF, DOCX, PPTX, Excel, and TXT
-## Quick Start
+- :material-web:{ .lg .middle } **Web Content**
-```python
-from semantica.parse import DocumentParser
+ ---
-# Initialize parser
-parser = DocumentParser()
+ Parse HTML, XML, and JavaScript-rendered pages with Selenium/Playwright
-# Parse with options
-docs = parser.parse(
- sources=["documents/"],
- formats=["pdf", "docx", "xlsx"],
- metadata={"source": "company_docs"}
-)
-
-# Access parsed data
-for doc in docs:
- print(f"Title: {doc.metadata.get('title')}")
- print(f"Author: {doc.metadata.get('author')}")
- print(f"Pages: {doc.metadata.get('pages')}")
- print(f"Text length: {len(doc.text)} characters")
-```
+- :material-code-json:{ .lg .middle } **Structured Data**
----
+ ---
-### PDFParser
+ Handle JSON, CSV, XML, and YAML with nested structure preservation
+- :material-email:{ .lg .middle } **Email Parsing**
-**Example Usage:**
+ ---
-```python
-from semantica.parse import PDFParser
-
-# Basic PDF parsing
-parser = PDFParser()
-doc = parser.parse("document.pdf")
-
-# Advanced PDF parsing with OCR
-parser = PDFParser(
- ocr_enabled=True,
- ocr_language="eng",
- extract_tables=True,
- extract_images=True,
- dpi=300
-)
-
-doc = parser.parse("scanned_document.pdf")
-
-# Access PDF-specific data
-print(f"Pages: {doc.metadata['pages']}")
-print(f"PDF version: {doc.metadata['pdf_version']}")
-print(f"Tables extracted: {len(doc.tables)}")
-
-# Access tables
-for i, table in enumerate(doc.tables):
- print(f"Table {i+1}:")
- print(table.to_dataframe())
-```
-
----
+ Extract headers, bodies, attachments, and thread structure from MIME messages
-### DOCXParser
+- :material-code-braces:{ .lg .middle } **Code Analysis**
+ ---
-**Example Usage:**
+ Parse source code (Python, JS, etc.) into ASTs, extracting functions and dependencies
-```python
-from semantica.parse import DOCXParser
+- :material-image:{ .lg .middle } **Media Processing**
-# Parse Word document
-parser = DOCXParser()
-doc = parser.parse("document.docx")
+ ---
-# With structure preservation
-parser = DOCXParser(
- preserve_structure=True,
- extract_tables=True,
- extract_images=True
-)
+ OCR for images and metadata extraction for audio/video files
-doc = parser.parse("report.docx")
+</div>
-# Access structure
-print(f"Headings: {doc.structure['headings']}")
-print(f"Sections: {len(doc.structure['sections'])}")
-print(f"Tables: {len(doc.tables)}")
-```
+!!! tip "When to Use"
+ - **Ingestion**: The first step after loading raw files to convert them into usable text/data
+ - **Data Extraction**: Pulling specific fields from structured files (JSON/CSV)
+ - **Content Analysis**: Analyzing codebases or email archives
+ - **OCR**: Extracting text from scanned documents or images
---
-### ExcelParser
+## ⚙️ Algorithms Used
+### Document Parsing
+- **PDF**: `pdfplumber` for precise layout preservation, table extraction, and image handling. Fallback to `PyPDF2`.
+- **Office (DOCX/PPTX/XLSX)**: XML-based parsing of OpenXML formats to extract text, styles, and properties.
+- **OCR**: Tesseract-based optical character recognition for image-based PDFs and image files.
-**Example Usage:**
+### Web Parsing
+- **DOM Traversal**: BeautifulSoup for static HTML parsing and element extraction.
+- **Headless Browser**: Selenium/Playwright for rendering dynamic JavaScript content before extraction.
+- **Content Cleaning**: Heuristic removal of boilerplates (navbars, footers, ads).
-```python
-from semantica.parse import ExcelParser
-
-# Parse Excel file
-parser = ExcelParser()
-doc = parser.parse("data.xlsx")
-
-# Parse specific sheets
-parser = ExcelParser(
- sheets=["Sheet1", "Data"],
- header_row=0,
- skip_empty_rows=True
-)
-
-doc = parser.parse("workbook.xlsx")
-
-# Access data
-for sheet_name, df in doc.dataframes.items():
- print(f"Sheet: {sheet_name}")
- print(f"Rows: {len(df)}, Columns: {len(df.columns)}")
- print(df.head())
-```
+### Code Parsing
+- **AST Traversal**: Abstract Syntax Tree parsing to identify classes, functions, and imports.
+- **Dependency Graphing**: Static analysis of import statements to build dependency networks.
+- **Comment Extraction**: Regex and parser-based extraction of docstrings and inline comments.
---
-### HTMLParser
+## Main Classes
+### DocumentParser
-**Example Usage:**
+Unified interface for document formats.
-```python
-from semantica.parse import HTMLParser
-
-# Parse HTML
-parser = HTMLParser()
-doc = parser.parse("page.html")
-
-# Advanced parsing
-parser = HTMLParser(
- extract_metadata=True,
- extract_links=True,
- remove_scripts=True,
- remove_styles=True
-)
-
-doc = parser.parse("article.html")
-
-# Access extracted data
-print(f"Title: {doc.metadata['title']}")
-print(f"Links: {len(doc.links)}")
-print(f"Main content: {doc.main_content}")
-```
-
----
-
-### JSONParser
+**Methods:**
+| Method | Description | Supported Formats |
+|--------|-------------|-------------------|
+| `parse_document(path)` | Auto-detect and parse | PDF, DOCX, PPTX, TXT |
+| `parse_pdf(path)` | PDF specific parsing | PDF |
+| `parse_docx(path)` | Word specific parsing | DOCX |
-**Example Usage:**
+**Example:**
```python
-from semantica.parse import JSONParser
+from semantica.parse import DocumentParser
-# Parse JSON
-parser = JSONParser()
-doc = parser.parse("data.json")
+parser = DocumentParser()
+doc = parser.parse_document("report.pdf")
+print(f"Title: {doc.metadata.title}")
+print(f"Text: {doc.text[:100]}...")
+```
-# Flatten nested JSON
-parser = JSONParser(
- flatten=True,
- separator=".",
- extract_schema=True
-)
+### WebParser
-doc = parser.parse("nested_data.json")
+Parses web content.
-# Access schema
-print(f"Schema: {doc.schema}")
-print(f"Flattened keys: {list(doc.flattened_data.keys())}")
-```
+**Methods:**
----
+| Method | Description |
+|--------|-------------|
+| `parse_html(url)` | Static HTML parsing |
+| `parse_dynamic(url)` | JS-rendered parsing |
-### ImageParser
+### StructuredDataParser
+Parses data files.
-**Example Usage:**
+**Methods:**
-```python
-from semantica.parse import ImageParser
+| Method | Description |
+|--------|-------------|
+| `parse_json(path)` | JSON with nesting |
+| `parse_csv(path)` | CSV with type inference |
-# Parse image with OCR
-parser = ImageParser(
- ocr_enabled=True,
- ocr_language="eng",
- detect_orientation=True
-)
+### CodeParser
-doc = parser.parse("scanned_page.jpg")
+Parses source code.
-# Access OCR results
-print(f"Extracted text: {doc.text}")
-print(f"Confidence: {doc.metadata['ocr_confidence']}")
-print(f"Orientation: {doc.metadata['orientation']}")
-```
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `parse_code(path)` | Extract AST & symbols |
+| `get_dependencies(path)` | Find imports |
---
-### CodeParser
+## Convenience Functions
+```python
+from semantica.parse import parse_document, parse_json, parse_web_content
-**Example Usage:**
+# Auto-detect format
+doc = parse_document("file.pdf")
-```python
-from semantica.parse import CodeParser
-
-# Parse source code
-parser = CodeParser(
- language="python",
- extract_functions=True,
- extract_classes=True,
- extract_docstrings=True
-)
-
-doc = parser.parse("module.py")
-
-# Access code structure
-print(f"Functions: {len(doc.functions)}")
-print(f"Classes: {len(doc.classes)}")
-
-for func in doc.functions:
- print(f"Function: {func.name}")
- print(f" Parameters: {func.parameters}")
- print(f" Docstring: {func.docstring}")
+# Parse specific types
+data = parse_json("data.json")
+web = parse_web_content("https://google.com")
```
---
-## Common Patterns
-
-### Pattern 1: Batch Parsing
-
-```python
-from semantica.parse import DocumentParser
-from pathlib import Path
-
-parser = DocumentParser()
+## Configuration
-# Get all files
-files = list(Path("documents/").rglob("*.*"))
+### Environment Variables
-# Parse in batches
-batch_size = 10
-for i in range(0, len(files), batch_size):
- batch = files[i:i+batch_size]
- docs = parser.parse(batch)
- # Process docs
+```bash
+export PARSE_OCR_ENABLED=true
+export PARSE_OCR_LANG=eng
+export PARSE_USER_AGENT="SemanticaBot/1.0"
```
-### Pattern 2: Format-Specific Parsing
+### YAML Configuration
-```python
-from semantica.parse import PDFParser, DOCXParser, ExcelParser
-
-# Route to appropriate parser
-def parse_document(file_path):
- if file_path.endswith('.pdf'):
- parser = PDFParser(ocr_enabled=True)
- elif file_path.endswith('.docx'):
- parser = DOCXParser(preserve_structure=True)
- elif file_path.endswith('.xlsx'):
- parser = ExcelParser()
- else:
- raise ValueError(f"Unsupported format: {file_path}")
+```yaml
+parse:
+ ocr:
+ enabled: true
+ language: eng
+
+ web:
+ user_agent: "MyBot/1.0"
+ timeout: 30
- return parser.parse(file_path)
+ pdf:
+ extract_tables: true
+ extract_images: false
```
-### Pattern 3: Error Handling
+---
-```python
-from semantica.parse import DocumentParser, ParseError
+## Integration Examples
-parser = DocumentParser()
+### Ingest & Parse Pipeline
-successful = []
-failed = []
+```python
+from semantica.ingest import Ingestor
+from semantica.parse import DocumentParser, ImageParser
+
+# 1. Ingest Raw File
+ingestor = Ingestor()
+file_path = ingestor.ingest("scan.png")
+
+# 2. Parse (with OCR)
+if file_path.endswith(".png"):
+ parser = ImageParser(ocr_enabled=True)
+ content = parser.parse_image(file_path)
+else:
+ parser = DocumentParser()
+ content = parser.parse_document(file_path)
+
+print(content.text)
+```
+
+---
-for file_path in file_paths:
- try:
- doc = parser.parse(file_path)
- successful.append(doc)
- except ParseError as e:
- print(f"Failed to parse {file_path}: {e}")
- failed.append((file_path, str(e)))
+## Best Practices
-print(f"Parsed: {len(successful)}, Failed: {len(failed)}")
-```
+1. **Disable OCR if not needed**: OCR is slow. Only enable it (`ocr_enabled=True`) if you expect scanned documents.
+2. **Use Specific Parsers**: If you know the format, use `parse_json` or `parse_pdf` directly for better type hinting.
+3. **Handle Encodings**: The parser tries to auto-detect encoding, but for CSV/TXT, explicitly specifying it is safer.
+4. **Clean Web Content**: Use `parse_web_content` which includes boilerplate removal, rather than raw HTML parsing.
---
-## Configuration
+## Troubleshooting
-```yaml
-# config.yaml - Parse Configuration
+**Issue**: `TesseractNotFoundError`
+**Solution**: Install Tesseract OCR on your system (`apt-get install tesseract-ocr` or brew).
-parse:
- pdf:
- ocr_enabled: true
- ocr_language: eng
- extract_tables: true
- extract_images: true
- dpi: 300
-
- docx:
- preserve_structure: true
- extract_tables: true
- extract_images: true
-
- excel:
- header_row: 0
- skip_empty_rows: true
- infer_types: true
-
- html:
- extract_metadata: true
- extract_links: true
- remove_scripts: true
- remove_styles: true
-
- image:
- ocr_enabled: true
- ocr_language: eng
- detect_orientation: true
-
- code:
- extract_functions: true
- extract_classes: true
- extract_docstrings: true
-```
+**Issue**: PDF tables are messy.
+**Solution**: Try `pdfplumber` settings in config or use specialized table extraction tools if layout is complex.
---
## See Also
-- [Ingest Module](ingest.md) - Data ingestion
-- [Normalize Module](normalize.md) - Data cleaning and normalization
-- [Semantic Extract Module](semantic_extract.md) - Entity and relationship extraction
+- [Ingest Module](ingest.md) - Handles file downloading/loading
+- [Split Module](split.md) - Chunks the parsed text
+- [Semantic Extract Module](semantic_extract.md) - Extracts entities from text
diff --git a/docs/reference/pipeline.md b/docs/reference/pipeline.md
index 17258790..b9432fb2 100644
--- a/docs/reference/pipeline.md
+++ b/docs/reference/pipeline.md
@@ -1,29 +1,79 @@
-# Pipeline Module
+# Pipeline
-Build and execute complex processing pipelines with support for parallel execution, error handling, and resource management.
+> **Robust orchestration engine for building, executing, and managing complex data processing workflows.**
-## Overview
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-pipe:{ .lg .middle } **Pipeline Builder**
+
+ ---
+
+ Fluent API for constructing complex DAG workflows
+
+- :material-play-circle:{ .lg .middle } **Execution Engine**
+
+ ---
+
+ Robust execution with status tracking and progress monitoring
+
+- :material-alert-circle-check:{ .lg .middle } **Error Handling**
+
+ ---
+
+ Configurable retry policies, fallbacks, and error recovery
+
+- :material-fast-forward:{ .lg .middle } **Parallel Execution**
+
+ ---
+
+ Execute independent steps in parallel for maximum performance
+
+- :material-cpu-64-bit:{ .lg .middle } **Resource Scheduling**
+
+ ---
+
+ Manage CPU/Memory allocation for resource-intensive tasks
-- **Pipeline Building**: Fluent API for pipeline construction
-- **Parallel Execution**: Multi-threaded/multi-process execution
-- **Error Handling**: Retry logic and failure recovery
-- **Resource Management**: Memory and CPU optimization
-- **Monitoring**: Progress tracking and logging
+- :material-file-document-edit:{ .lg .middle } **Templates**
+
+ ---
+
+ Pre-built templates for common workflows (ETL, GraphRAG)
+
+</div>
+
+!!! tip "When to Use"
+ - **ETL Workflows**: Ingest -> Parse -> Split -> Embed -> Store
+ - **Graph Construction**: Extract Entities -> Extract Relations -> Build Graph
+ - **Batch Processing**: Processing large volumes of documents reliably
---
-## Algorithms Used
+## ⚙️ Algorithms Used
+
+### Execution Management
+- **DAG Topological Sort**: Determines execution order of steps
+- **State Management**: Tracks `PENDING`, `RUNNING`, `COMPLETED`, `FAILED` states
+- **Checkpointing**: Saves intermediate results to allow resuming failed pipelines
-### Execution Algorithms
-- **DAG (Directed Acyclic Graph) Execution**: Topological sort for step ordering
-- **Parallel Execution**: Thread pool with work stealing
-- **Dependency Resolution**: Kahn's algorithm for topological ordering
-- **Resource Scheduling**: Greedy scheduling with priority queue
+### Parallelism
+- **ThreadPoolExecutor**: For I/O-bound tasks (network requests, DB writes)
+- **ProcessPoolExecutor**: For CPU-bound tasks (parsing, embedding generation)
+- **Dependency Resolution**: Identifies steps that can run concurrently
### Error Handling
-- **Exponential Backoff**: Retry with increasing delays: `delay = base * 2^attempt`
-- **Circuit Breaker**: Fail fast after threshold failures
-- **Checkpoint/Resume**: State persistence for long-running pipelines
+- **Exponential Backoff**: `wait = base * (factor ^ attempt)`
+- **Jitter**: Randomization to prevent thundering herd problem
+- **Circuit Breaker**: Stops execution after threshold failures to prevent cascading issues
+
+### Resource Scheduling
+- **Token Bucket**: Rate limiting for API calls
+- **Semaphore**: Concurrency limiting for resource constraints
+- **Priority Queue**: Scheduling critical tasks first
---
@@ -31,97 +81,204 @@ Build and execute complex processing pipelines with support for parallel executi
### PipelineBuilder
+Fluent interface for constructing pipelines.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `add_step(name, processor)` | Add pipeline step | Step registration |
-| `add_parallel_steps(steps)` | Add parallel steps | Parallel branch creation |
-| `build()` | Build pipeline | DAG construction + validation |
-| `execute(input_data)` | Execute pipeline | Topological execution |
-| `set_error_handler(handler)` | Set error handler | Handler registration |
+| Method | Description |
+|--------|-------------|
+| `add_step(name, func)` | Add a processing step |
+| `add_dependency(step, dep)` | Define execution order |
+| `set_error_handler(handler)` | Configure error handling |
+| `build()` | Create immutable Pipeline object |
**Example:**
```python
from semantica.pipeline import PipelineBuilder
-from semantica.ingest import FileIngestor
-from semantica.parse import DocumentParser
-from semantica.semantic_extract import NERExtractor
-
-pipeline = PipelineBuilder() \\
- .add_step("ingest", FileIngestor(recursive=True)) \\
- .add_step("parse", DocumentParser()) \\
- .add_step("extract", NERExtractor()) \\
- .add_step("build_kg", GraphBuilder()) \\
- .build()
-result = pipeline.execute(sources=["documents/"])
-print(f"Processed {result.stats['documents_processed']} documents")
+pipeline = (
+ PipelineBuilder()
+ .add_step("ingest", ingest_func)
+ .add_step("parse", parse_func)
+ .add_step("embed", embed_func)
+ .add_dependency("parse", "ingest") # parse depends on ingest
+ .add_dependency("embed", "parse") # embed depends on parse
+ .build()
+)
```
----
-
### ExecutionEngine
+Executes pipelines and manages lifecycle.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `execute(pipeline, data)` | Execute pipeline | DAG traversal |
-| `execute_parallel(steps, data)` | Parallel execution | Thread/process pool |
-| `execute_sequential(steps, data)` | Sequential execution | Linear execution |
-| `schedule_steps(dag)` | Schedule execution | Topological sort |
+| Method | Description |
+|--------|-------------|
+| `execute(pipeline, input)` | Run pipeline synchronously |
+| `execute_async(pipeline)` | Run in background |
+| `resume(execution_id)` | Resume failed execution |
+| `get_status(execution_id)` | Check progress |
----
+**Example:**
+
+```python
+from semantica.pipeline import ExecutionEngine
+
+engine = ExecutionEngine()
+result = engine.execute(pipeline, input_data={"files": ["doc.pdf"]})
+
+if result.status == "COMPLETED":
+ print("Success:", result.output)
+else:
+ print("Failed:", result.error)
+```
### FailureHandler
+Manages retries and error recovery.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `handle_failure(error, context)` | Handle step failure | Strategy-based handling |
-| `retry(step, max_retries)` | Retry failed step | Exponential backoff |
-| `skip(step)` | Skip failed step | Continue execution |
-| `abort(pipeline)` | Abort pipeline | Graceful shutdown |
+| Method | Description |
+|--------|-------------|
+| `handle_error(error, context)` | Process error |
+| `should_retry(attempt)` | Check retry policy |
+
+**Configuration:**
-**Retry Strategy:**
+```python
+from semantica.pipeline import RetryPolicy
+
+policy = RetryPolicy(
+ max_retries=3,
+ backoff_factor=2.0,
+ exceptions=[NetworkError, TimeoutError]
+)
```
-delay = base_delay * (2 ** attempt) + random_jitter
-max_delay = min(delay, max_delay)
+
+### ParallelismManager
+
+Manages concurrent execution.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `execute_parallel(tasks)` | Run tasks concurrently |
+| `map(func, items)` | Parallel map operation |
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.pipeline import build_linear_pipeline
+
+# Quick linear pipeline
+pipeline = build_linear_pipeline([
+ step1_func,
+ step2_func,
+ step3_func
+])
```
---
## Configuration
-```yaml
-# config.yaml - Pipeline Configuration
+### Environment Variables
+```bash
+export PIPELINE_MAX_WORKERS=4
+export PIPELINE_DEFAULT_TIMEOUT=300
+export PIPELINE_CHECKPOINT_DIR=./checkpoints
+```
+
+### YAML Configuration
+
+```yaml
pipeline:
execution:
- parallel: true
max_workers: 4
- timeout: 3600 # seconds
+ timeout_seconds: 300
- error_handling:
- strategy: retry # retry, skip, abort
- max_retries: 3
- retry_delay: 1 # seconds
- exponential_backoff: true
+ retry:
+ default_retries: 3
+ backoff_factor: 1.5
- monitoring:
- log_level: INFO
- progress_bar: true
- checkpoint_interval: 100 # steps
+ resources:
+ max_memory_mb: 4096
```
---
+## Integration Examples
+
+### Complete RAG Ingestion Pipeline
+
+```python
+from semantica.pipeline import PipelineBuilder, ExecutionEngine
+from semantica.ingest import Ingestor
+from semantica.split import TextSplitter
+from semantica.embeddings import EmbeddingGenerator
+from semantica.vector_store import VectorStore
+
+# 1. Define Steps
+def ingest(data):
+ return Ingestor().ingest(data['path'])
+
+def split(data):
+ return TextSplitter().split(data['text'])
+
+def embed(data):
+ return EmbeddingGenerator().generate(data['chunks'])
+
+def store(data):
+ return VectorStore().store(data['embeddings'])
+
+# 2. Build Pipeline
+pipeline = (
+ PipelineBuilder()
+ .add_step("ingest", ingest)
+ .add_step("split", split)
+ .add_step("embed", embed)
+ .add_step("store", store)
+ .add_dependency("split", "ingest")
+ .add_dependency("embed", "split")
+ .add_dependency("store", "embed")
+ .build()
+)
+
+# 3. Execute
+engine = ExecutionEngine()
+result = engine.execute(pipeline, {"path": "document.pdf"})
+```
+
+---
+
+## Best Practices
+
+1. **Idempotency**: Ensure steps are idempotent (can be run multiple times without side effects) to support retries.
+2. **Granularity**: Keep steps focused on a single task. Smaller steps are easier to debug and retry.
+3. **Context Passing**: Use the execution context to pass metadata between steps, not just return values.
+4. **Error Handling**: Always define specific exceptions for retries; don't retry on `ValueError` or `TypeError`.
+
+---
+
+## Troubleshooting
+
+**Issue**: Pipeline stuck in `RUNNING` state.
+**Solution**: Check for deadlocks in dependency graph or infinite loops in steps. Use `timeout_seconds`.
+
+**Issue**: `PickleError` during parallel execution.
+**Solution**: Ensure all data passed between steps is serializable. Avoid passing open file handles or database connections.
+
+---
+
## See Also
-- [Core Module](core.md)
+- [Ingest Module](ingest.md) - Common first step
+- [Split Module](split.md) - Common processing step
+- [Vector Store Module](vector_store.md) - Common sink step
diff --git a/docs/reference/reasoning.md b/docs/reference/reasoning.md
index c94e1105..57b766e8 100644
--- a/docs/reference/reasoning.md
+++ b/docs/reference/reasoning.md
@@ -1,29 +1,81 @@
-# Reasoning Module
+# Reasoning
-Perform logical inference and reasoning on knowledge graphs using rule-based and deductive reasoning engines with support for forward/backward chaining.
+> **Advanced inference engine supporting Rule-based, SPARQL, Abductive, and Deductive reasoning strategies.**
-## Overview
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-graph-outline:{ .lg .middle } **Rule-Based Inference**
+
+ ---
+
+ Forward and Backward chaining with Rete algorithm optimization
+
+- :material-database-search:{ .lg .middle } **SPARQL Reasoning**
+
+ ---
+
+ Query expansion and property chain inference
+
+- :material-lightbulb-question:{ .lg .middle } **Abductive Reasoning**
+
+ ---
+
+ Generate hypotheses to explain observations (Sherlock Holmes style)
+
+- :material-check-decagram:{ .lg .middle } **Deductive Reasoning**
+
+ ---
+
+ Logical proof generation and theorem proving
+
+- :material-text-box-search:{ .lg .middle } **Explanation**
+
+ ---
-- **Rule-Based Reasoning**: Apply logical rules to derive new facts
-- **Deductive Reasoning**: Infer conclusions from premises
-- **Forward Chaining**: Data-driven reasoning
-- **Backward Chaining**: Goal-driven reasoning
-- **SWRL Support**: Semantic Web Rule Language
+ Generate natural language explanations for inferred facts
+
+- :material-flash:{ .lg .middle } **Rete Algorithm**
+
+ ---
+
+ High-performance pattern matching for large rule sets
+
+</div>
+
+!!! tip "When to Use"
+ - **Inference**: Deriving new facts from existing data (e.g., `Parent(A,B) & Parent(B,C) -> Grandparent(A,C)`)
+ - **Query Expansion**: Finding results that aren't explicitly stored but implied
+ - **Hypothesis Generation**: Finding potential causes for an observed event
+ - **Validation**: Checking logical consistency of the knowledge graph
---
-## Algorithms Used
+## ⚙️ Algorithms Used
-### Inference Algorithms
-- **Forward Chaining (Rete Algorithm)**: Efficient pattern matching, O(RFP) complexity where R=rules, F=facts, P=patterns
-- **Backward Chaining**: Goal-directed reasoning with SLD resolution
-- **Tableau Algorithm**: Description Logic reasoning
-- **Resolution**: First-order logic inference
+### Rule-Based Inference
+- **Forward Chaining**: Data-driven. Apply rules to facts to derive new facts until saturation.
+- **Backward Chaining**: Goal-driven. Start from a goal and work backward to find supporting facts.
+- **Bidirectional Chaining**: Meet-in-the-middle strategy for complex paths.
-### Rule Matching
-- **Rete Network**: Compiled rule network for efficient matching
-- **Pattern Matching**: Unification algorithm for variable binding
-- **Conflict Resolution**: Priority-based rule selection
+### Rete Algorithm
+- **Alpha Nodes**: Filter facts by single attributes (e.g., `type=Person`).
+- **Beta Nodes**: Join results from Alpha nodes (e.g., `Person.id == Parent.child_id`).
+- **Memory**: Stores partial matches to avoid re-computation.
+- **Conflict Resolution**: Priority-based selection when multiple rules match.
+
+### SPARQL Reasoning
+- **Query Rewriting**: Modifying queries to include inferred patterns.
+- **Property Paths**: Handling transitive relationships (`foaf:knows+`).
+- **Materialization**: Pre-computing inferred triples for fast read performance.
+
+### Abductive Reasoning
+- **Hypothesis Generation**: Finding rules where the conclusion matches the observation.
+- **Ranking**: Scoring hypotheses by Simplicity, Plausibility, and Coverage.
+- **Consistency Check**: Ensuring hypotheses don't contradict known facts.
---
@@ -31,124 +83,167 @@ Perform logical inference and reasoning on knowledge graphs using rule-based and
### InferenceEngine
+General-purpose inference engine supporting multiple strategies.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `forward_chain(kg, rules)` | Forward chaining inference | Rete algorithm |
-| `backward_chain(kg, goal)` | Backward chaining | SLD resolution |
-| `infer(kg, rules)` | General inference | Auto-select forward/backward |
-| `apply_rules(facts, rules)` | Apply rule set | Pattern matching + unification |
-| `explain_inference(fact)` | Explain derivation | Proof tree generation |
+| `infer(facts, rules)` | Derive new facts | Forward Chaining |
+| `query(goal, rules)` | Check if goal is true | Backward Chaining |
**Example:**
```python
-from semantica.reasoning import InferenceEngine, RuleManager
-
-engine = InferenceEngine(
- strategy="forward", # forward, backward, hybrid
- max_iterations=100,
- explain_inferences=True
-)
-
-rule_manager = RuleManager()
-rule_manager.add_rule(
- "IF ?x foundedBy ?y THEN ?y founder_of ?x"
-)
-
-# Forward chaining
-new_facts = engine.forward_chain(kg, rule_manager)
-print(f"Inferred {len(new_facts)} new facts")
-
-# Explain inference
-for fact in new_facts[:5]:
- explanation = engine.explain_inference(fact)
- print(f"{fact}: {explanation}")
+from semantica.reasoning import InferenceEngine, Rule
+
+rules = [
+ Rule("Grandparent", "Parent(x, y) & Parent(y, z) -> Grandparent(x, z)")
+]
+facts = ["Parent(Alice, Bob)", "Parent(Bob, Charlie)"]
+
+engine = InferenceEngine()
+inferred = engine.infer(facts, rules)
+# Result: ["Grandparent(Alice, Charlie)"]
```
----
+### ReteEngine
+
+High-performance pattern matching engine.
+
+**Methods:**
-### RuleManager
+| Method | Description |
+|--------|-------------|
+| `add_rule(rule)` | Compile rule into network |
+| `add_fact(fact)` | Propagate fact through network |
+| `get_activations()` | Get triggered rules |
+### SPARQLReasoner
+
+SPARQL-based reasoner for RDF graphs.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `add_rule(rule)` | Add inference rule | Rule parsing + validation |
-| `remove_rule(rule_id)` | Remove rule | Rule deletion |
-| `load_rules(filename)` | Load rules from file | SWRL/custom format parsing |
-| `validate_rules()` | Validate rule set | Consistency checking |
-| `compile_rules()` | Compile to Rete network | Rete compilation |
+| Method | Description |
+|--------|-------------|
+| `expand_query(query)` | Rewrite query with inference |
+| `materialize(graph)` | Add inferred triples to graph |
-**Rule Syntax:**
-```
-IF <condition> THEN <conclusion>
+### AbductiveReasoner
-Examples:
-IF ?x type Person AND ?x worksFor ?y THEN ?y employs ?x
-IF ?x foundedBy ?y AND ?y type Person THEN ?x type Organization
-```
+Generates explanations for observations.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `abduce(observation)` | Generate hypotheses |
+| `rank_hypotheses(hyps)` | Score and sort |
**Example:**
```python
-from semantica.reasoning import RuleManager
+from semantica.reasoning import AbductiveReasoner
-rules = RuleManager()
+reasoner = AbductiveReasoner(rules)
+hypotheses = reasoner.abduce("Pavement is wet")
+# Result: ["It rained", "Sprinkler was on"]
+```
-# Add rules
-rules.add_rule("IF ?x type Company AND ?x foundedBy ?y THEN ?y founder_of ?x")
-rules.add_rule("IF ?x founder_of ?y AND ?y type Company THEN ?x type Entrepreneur")
+### ExplanationGenerator
-# Load from file
-rules.load_rules("rules.swrl")
+Explains *why* a fact was inferred.
-# Validate
-is_valid, errors = rules.validate_rules()
-```
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `explain(fact)` | Generate reasoning trace |
+| `visualize_trace(trace)` | Graph visualization |
---
-### DeductiveReasoner
+## Convenience Functions
+```python
+from semantica.reasoning import forward_chain, backward_chain, generate_explanation
-**Methods:**
+# Quick inference
+new_facts = forward_chain(facts, rules)
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `reason(kg, axioms)` | Perform deductive reasoning | Tableau algorithm |
-| `check_entailment(kg, statement)` | Check if statement is entailed | Subsumption testing |
-| `find_inconsistencies(kg)` | Find logical contradictions | Consistency checking |
-| `classify(kg)` | Compute class hierarchy | Classification algorithm |
+# Explain result
+explanation = generate_explanation(new_facts[0], rules)
+print(explanation.text)
+```
---
## Configuration
-```yaml
-# config.yaml - Reasoning Configuration
+### Environment Variables
+
+```bash
+export REASONING_MAX_ITERATIONS=100
+export REASONING_STRATEGY=rete
+export REASONING_TIMEOUT=30
+```
+
+### YAML Configuration
+```yaml
reasoning:
- inference:
- strategy: forward # forward, backward, hybrid
- max_iterations: 100
- explain_inferences: true
-
- rules:
- format: swrl # swrl, custom
- validate_on_load: true
+ default_strategy: rete
+ max_depth: 10
+
+ rete:
+ node_sharing: true
- deductive:
- reasoner: hermit # hermit, pellet
- check_consistency: true
+ abductive:
+ max_hypotheses: 5
```
---
+## Integration Examples
+
+### Knowledge Graph Enrichment
+
+```python
+from semantica.reasoning import InferenceEngine, Rule
+from semantica.kg import KnowledgeGraph
+
+# 1. Define Ontology Rules
+rules = [
+ Rule("SymmetricSibling", "Sibling(x, y) -> Sibling(y, x)"),
+ Rule("TransitiveAncestor", "Ancestor(x, y) & Ancestor(y, z) -> Ancestor(x, z)")
+]
+
+# 2. Load Graph
+kg = KnowledgeGraph()
+facts = kg.get_all_triples()
+
+# 3. Run Inference
+engine = InferenceEngine()
+inferred_triples = engine.infer(facts, rules)
+
+# 4. Update Graph
+kg.add_triples(inferred_triples)
+```
+
+---
+
+## Best Practices
+
+1. **Limit Recursion**: Be careful with recursive rules (e.g., `A(x,y) -> A(y,x)`) which can cause infinite loops in naive implementations.
+2. **Use Rete for Scale**: For >100 rules or >10k facts, always use the Rete engine.
+3. **Materialize vs. Query**: Materialize (pre-compute) for read-heavy workloads; Query-rewrite for write-heavy workloads.
+4. **Validate Rules**: Ensure rules are logically consistent to avoid exploding the fact space.
+
+---
+
## See Also
-- [Knowledge Graph Module](kg.md)
-- [Ontology Module](ontology.md)
+- [Ontology Module](ontology.md) - Source of schema-based rules
+- [Triple Store Module](triple_store.md) - Backend for SPARQL reasoning
+- [KG QA Module](kg_qa.md) - Uses reasoning for consistency checking
diff --git a/docs/reference/seed.md b/docs/reference/seed.md
new file mode 100644
index 00000000..d7d85b75
--- /dev/null
+++ b/docs/reference/seed.md
@@ -0,0 +1,193 @@
+# Seed
+
+> **Seed data management system for initializing Knowledge Graphs from verified sources.**
+
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-database-import:{ .lg .middle } **Multi-Source Loading**
+
+ ---
+
+ Load seed data from CSV, JSON, Databases, and APIs
+
+- :material-graph-outline:{ .lg .middle } **Foundation Graph**
+
+ ---
+
+ Create reliable foundation graphs to bootstrap your KG
+
+- :material-merge:{ .lg .middle } **Data Integration**
+
+ ---
+
+ Merge seed data with extracted data using configurable strategies
+
+- :material-check-all:{ .lg .middle } **Validation**
+
+ ---
+
+ Validate seed data quality and schema compliance
+
+- :material-git:{ .lg .middle } **Versioning**
+
+ ---
+
+ Manage versions of seed data sources
+
+- :material-export:{ .lg .middle } **Export**
+
+ ---
+
+ Export seed data to standard formats
+
+</div>
+
+!!! tip "When to Use"
+ - **Bootstrapping**: When starting a new KG and you have existing structured data (taxonomies, user lists, product catalogs).
+ - **Reference Data**: To load immutable reference data (countries, codes, constants).
+ - **Testing**: To load consistent test datasets for development.
+
+---
+
+## ⚙️ Algorithms Used
+
+### Data Loading
+- **Format Detection**: Auto-detection of CSV delimiters, JSON structure
+- **Streaming**: Row-by-row processing for large files
+- **Normalization**: Type conversion and encoding handling
+
+### Integration & Merging
+- **Seed-First Strategy**: Seed data overrides extracted data (Trust Seed)
+- **Extracted-First Strategy**: Extracted data overrides seed (Trust Extraction)
+- **Smart Merge**: Property-level merging with conflict resolution
+- **ID Matching**: Entity resolution between seed and extracted entities
+
+### Validation
+- **Schema Validation**: Template-based structure checking
+- **Constraint Checking**: Required field and type validation
+- **Consistency Check**: Reference integrity (relationships point to existing entities)
+
+---
+
+## Main Classes
+
+### SeedDataManager
+
+Coordinator for all seed data operations.
+
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `register_source(name, type, path)` | Add data source |
+| `create_foundation_graph()` | Build KG from sources |
+| `validate_quality(graph)` | Check data quality |
+| `integrate(seed_kg, extracted_kg)` | Merge graphs |
+
+**Example:**
+
+```python
+from semantica.seed import SeedDataManager
+
+manager = SeedDataManager()
+manager.register_source("countries", "csv", "data/countries.csv")
+foundation_kg = manager.create_foundation_graph()
+```
+
+### SeedDataSource
+
+Data class defining a source.
+
+**Attributes:**
+- `name`: Source identifier
+- `type`: `csv`, `json`, `api`, `sql`
+- `path`: File path or connection string
+- `config`: Parsing options
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.seed import register_seed_source, create_foundation
+
+# Quick setup
+register_seed_source("products", "json", "products.json")
+kg = create_foundation()
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+export SEED_DATA_DIR=./data/seed
+export SEED_MERGE_STRATEGY=seed_first
+```
+
+### YAML Configuration
+
+```yaml
+seed:
+ sources:
+ - name: "employees"
+ type: "csv"
+ path: "./data/employees.csv"
+
+ merge:
+ strategy: "seed_first"
+
+ validation:
+ strict: true
+```
+
+---
+
+## Integration Examples
+
+### Bootstrapping a KG
+
+```python
+from semantica.seed import SeedDataManager
+from semantica.ingest import Ingestor
+from semantica.kg import KnowledgeGraph
+
+# 1. Load Foundation (Seed)
+seed_manager = SeedDataManager()
+seed_manager.register_source("taxonomy", "json", "taxonomy.json")
+foundation_kg = seed_manager.create_foundation_graph()
+
+# 2. Ingest New Data
+ingestor = Ingestor()
+new_data = ingestor.ingest("news_articles.pdf")
+
+# 3. Merge
+final_kg = seed_manager.integrate_seed_extracted(
+ seed_graph=foundation_kg,
+ extracted_data=new_data,
+ strategy="seed_first" # Keep taxonomy strict
+)
+```
+
+---
+
+## Best Practices
+
+1. **Trust Seed Data**: Usually, seed data is verified. Use `seed_first` merge strategy.
+2. **Version Control**: Keep seed data files in version control (git).
+3. **Validate Schema**: Ensure seed data matches your target ontology.
+4. **Clean IDs**: Use consistent ID schemes in seed data to facilitate merging.
+
+---
+
+## See Also
+
+- [Ingest Module](ingest.md) - Loading unstructured data
+- [Knowledge Graph Module](kg.md) - The target graph structure
+- [Deduplication Module](deduplication.md) - Handling duplicates during merge
diff --git a/docs/reference/semantic_extract.md b/docs/reference/semantic_extract.md
index 334e454b..e99cf05b 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,352 +82,147 @@
### NamedEntityRecognizer
+Coordinator for entity extraction.
**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
-ner = NamedEntityRecognizer(
- model="transformer", # or "spacy", "stanza", "custom"
- lang="en",
- entities=["PERSON", "ORG", "LOC", "DATE", "MONEY"],
- confidence_threshold=0.7,
- use_llm_enhancement=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)
+ner = NamedEntityRecognizer()
+entities = ner.extract_entities("Elon Musk leads SpaceX.")
+# [Entity(text="Elon Musk", label="PERSON"), Entity(text="SpaceX", label="ORG")]
```
----
-
### RelationExtractor
+Extracts relationships between entities.
**Methods:**
-| 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 |
-
-**Algorithms:**
-
-- **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
-extractor = RelationExtractor(
- strategy="hybrid", # "rule-based", "ml-based", "hybrid", "llm-based"
- confidence_threshold=0.7,
- max_relationships_per_entity=10
-)
-
-relationships = extractor.extract(text, entities)
-
-for rel in relationships:
- print(f"{rel.subject} --[{rel.predicate}]--> {rel.object}")
-# Output:
-# Apple Inc. --[founded_by]--> Steve Jobs
+re = RelationExtractor()
+relations = re.extract_relations(text, entities)
+# [Relation(source="Elon Musk", target="SpaceX", type="leads")]
```
----
-
### EventDetector
+Identifies events.
**Methods:**
-| 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 |
-
-**Event Types Supported:**
-- ACQUISITION, FOUNDING, PARTNERSHIP, ANNOUNCEMENT
-- MERGER, IPO, BANKRUPTCY, LAWSUIT
-- PRODUCT_LAUNCH, CONFERENCE, ELECTION
-- Custom event types via configuration
-
-**Example:**
-
-```python
-from semantica.semantic_extract import EventDetector
-
-detector = EventDetector(
- event_types=["ACQUISITION", "FOUNDING", "PARTNERSHIP"],
- min_confidence=0.75
-)
-
-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]}")
-```
-
----
+| Method | Description |
+|--------|-------------|
+| `detect_events(text)` | Find events |
### TripleExtractor
+Extracts RDF triples.
**Methods:**
-| 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 |
-
-**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
-
-**Example:**
-
-```python
-from semantica.semantic_extract import TripleExtractor
-
-extractor = TripleExtractor(
- format="rdf", # "rdf", "turtle", "n-triples", "json-ld"
- validate_triples=True,
- namespace="http://example.org/"
-)
-
-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
-```
+| Method | Description |
+|--------|-------------|
+| `extract_triples(text)` | Get (S, P, O) tuples |
---
-### 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 build
+
+# All-in-one extraction
+result = build(
+ "Apple released the iPhone in 2007.",
+ extract_entities=True,
+ extract_relations=True,
+ extract_events=True
)
-resolved_entities = resolver.resolve(text, entities)
+print(result['triples'])
```
---
-### SemanticAnalyzer
-
-
-**Methods:**
-
-| 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 |
-
-**Example:**
-
-```python
-from semantica.semantic_extract import SemanticAnalyzer
-
-analyzer = SemanticAnalyzer()
-
-analysis = analyzer.analyze_semantics(
- text=text,
- entities=entities,
- relationships=relationships
-)
-
-print(f"Coherence score: {analysis.coherence_score:.2f}")
-print(f"Semantic roles: {analysis.semantic_roles}")
-```
-
----
-
-### 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
+ model: dslim/bert-base-NER
+ min_confidence: 0.7
- 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
-
- 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
-### 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
+### KG Population Pipeline
+
+```python
+from semantica.semantic_extract import build
+from semantica.kg import KnowledgeGraph
+
+# 1. Extract
+text = "Google was founded by Larry Page and Sergey Brin."
+data = build(text, extract_triples=True)
+
+# 2. Populate KG
+kg = KnowledgeGraph()
+for triple in data['triples']:
+ kg.add_triple(
+ subject=triple.subject,
+ predicate=triple.predicate,
+ object=triple.object
+ )
+```
+
+---
-### 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/docs/reference/split.md b/docs/reference/split.md
new file mode 100644
index 00000000..90bcfc9d
--- /dev/null
+++ b/docs/reference/split.md
@@ -0,0 +1,809 @@
+# Split
+
+> **Comprehensive document chunking and splitting for optimal processing with 15+ methods including KG-aware, semantic, and structural chunking.**
+
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-content-cut:{ .lg .middle } **Multiple Methods**
+
+ ---
+
+ 15+ chunking methods: recursive, semantic, entity-aware, relation-aware, and more
+
+- :material-graph:{ .lg .middle } **KG-Aware Chunking**
+
+ ---
+
+ Preserve entities, relationships, and graph structure for GraphRAG workflows
+
+- :material-brain:{ .lg .middle } **Semantic Chunking**
+
+ ---
+
+ Intelligent boundary detection using embeddings and NLP
+
+- :material-file-tree:{ .lg .middle } **Structural Chunking**
+
+ ---
+
+ Respect document structure: headings, paragraphs, lists, tables
+
+- :material-check-circle:{ .lg .middle } **Quality Validation**
+
+ ---
+
+ Chunk quality assessment and validation
+
+- :material-source-branch:{ .lg .middle } **Provenance Tracking**
+
+ ---
+
+ Track chunk origins for data lineage
+
+</div>
+
+!!! tip "Choosing the Right Method"
+ - **Standard Documents**: Use `recursive` or `sentence` for general text
+ - **GraphRAG**: Use `entity_aware` or `relation_aware` to preserve knowledge
+ - **Semantic Coherence**: Use `semantic_transformer` for topic-based chunks
+ - **Structured Docs**: Use `structural` for documents with headings/sections
+ - **Large Documents**: Use `hierarchical` for multi-level chunking
+
+---
+
+## ⚙️ Algorithms Used
+
+### Standard Splitting Algorithms
+- **Recursive Splitting**: Separator hierarchy (`\n\n`, `\n`, ` `, ``) with greedy splitting
+- **Token Counting**: BPE tokenization using tiktoken or transformers
+- **Sentence Segmentation**: NLTK punkt, spaCy sentencizer, or regex-based
+- **Paragraph Detection**: Double newline detection with whitespace normalization
+- **Character Splitting**: Fixed-size character chunks with overlap
+- **Word Splitting**: Whitespace tokenization with word boundary preservation
+
+### Semantic Chunking Algorithms
+- **Semantic Boundary Detection**:
+ - Sentence transformer embeddings (384-1024 dim)
+ - Cosine similarity between consecutive sentences
+ - Threshold-based boundary detection (default: 0.7)
+- **LLM-based Splitting**:
+ - Prompt engineering for optimal split point detection
+ - Context window management
+ - Coherence scoring
+
+### KG/Ontology Chunking Algorithms
+- **Entity Boundary Detection**:
+ - NER-based entity extraction (spaCy, LLM)
+ - Entity span tracking
+ - Boundary preservation (no entity splitting)
+- **Triple Preservation**:
+ - Graph-based triple integrity checking
+ - Subject-predicate-object span tracking
+ - Relationship boundary preservation
+- **Graph Centrality Analysis**:
+ - Degree centrality: `C_D(v) = deg(v) / (n-1)`
+ - Betweenness centrality: `C_B(v) = Σ(σ_st(v) / σ_st)`
+ - Closeness centrality: `C_C(v) = (n-1) / Σd(v,u)`
+ - Eigenvector centrality: Power iteration method
+- **Community Detection**:
+ - Louvain algorithm: Modularity optimization O(n log n)
+ - Leiden algorithm: Improved Louvain with refinement
+ - Modularity calculation: `Q = (1/2m) Σ[A_ij - k_i*k_j/2m]δ(c_i,c_j)`
+
+### Structural Chunking Algorithms
+- **Heading Detection**: Markdown/HTML heading parsing
+- **List Detection**: Ordered/unordered list identification
+- **Table Detection**: Table boundary identification
+- **Section Hierarchy**: Tree-based section structure
+
+### Validation Algorithms
+- **Chunk Size Validation**: Min/max size checking
+- **Overlap Validation**: Overlap percentage calculation
+- **Completeness Check**: Coverage verification
+- **Quality Scoring**: Multi-factor quality assessment
+
+---
+
+## Main Classes
+
+### TextSplitter
+
+Unified text splitter with method parameter for all chunking strategies.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `split(text)` | Split text using configured method | Method-specific algorithm |
+| `split_documents(documents)` | Batch split documents | Parallel processing |
+| `split_with_metadata(text, metadata)` | Split with metadata preservation | Metadata propagation |
+| `validate_chunks(chunks)` | Validate chunk quality | Quality assessment |
+
+**Supported Methods:**
+
+| Category | Methods |
+|----------|---------|
+| **Standard** | recursive, token, sentence, paragraph, character, word |
+| **Semantic** | semantic_transformer, llm, huggingface, nltk |
+| **KG/Ontology** | entity_aware, relation_aware, graph_based, ontology_aware |
+| **Advanced** | hierarchical, community_detection, centrality_based, subgraph, topic_based |
+
+**Configuration Options:**
+
+```python
+TextSplitter(
+ method="recursive", # Chunking method
+ chunk_size=1000, # Target chunk size (characters/tokens)
+ chunk_overlap=200, # Overlap between chunks
+ length_function=len, # Function to measure chunk size
+ separators=["\n\n", "\n", " ", ""], # For recursive method
+ keep_separator=True, # Keep separators in chunks
+ add_start_index=True, # Add start index to metadata
+ strip_whitespace=True, # Strip whitespace from chunks
+
+ # Semantic chunking options
+ embedding_model="all-MiniLM-L6-v2", # For semantic_transformer
+ similarity_threshold=0.7, # Semantic boundary threshold
+
+ # Entity-aware options
+ ner_method="spacy", # NER method (spacy, llm, transformers)
+ preserve_entities=True, # Don't split entities
+
+ # LLM options
+ llm_provider="openai", # LLM provider
+ llm_model="gpt-4", # LLM model
+
+ # Graph-based options
+ centrality_method="degree", # Centrality measure
+ community_algorithm="louvain", # Community detection algorithm
+)
+```
+
+**Example:**
+
+```python
+from semantica.split import TextSplitter
+
+# Standard recursive splitting
+splitter = TextSplitter(
+ method="recursive",
+ chunk_size=1000,
+ chunk_overlap=200
+)
+chunks = splitter.split(long_text)
+
+for i, chunk in enumerate(chunks):
+ print(f"Chunk {i}: {len(chunk.text)} chars")
+ print(f"Metadata: {chunk.metadata}")
+
+# Entity-aware for GraphRAG
+splitter = TextSplitter(
+ method="entity_aware",
+ ner_method="llm",
+ chunk_size=1000,
+ preserve_entities=True
+)
+chunks = splitter.split(text)
+
+# Semantic chunking
+splitter = TextSplitter(
+ method="semantic_transformer",
+ embedding_model="all-MiniLM-L6-v2",
+ similarity_threshold=0.7
+)
+chunks = splitter.split(text)
+
+# Hierarchical chunking
+splitter = TextSplitter(
+ method="hierarchical",
+ chunk_sizes=[2000, 1000, 500], # Multi-level
+ chunk_overlaps=[400, 200, 100]
+)
+chunks = splitter.split(text)
+```
+
+---
+
+### SemanticChunker
+
+Semantic-based chunking using embeddings and similarity.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `chunk(text)` | Chunk by semantic boundaries | Embedding similarity |
+| `find_boundaries(sentences)` | Find semantic boundaries | Threshold-based detection |
+| `calculate_similarity(sent1, sent2)` | Calculate similarity | Cosine similarity |
+
+**Example:**
+
+```python
+from semantica.split import SemanticChunker
+
+chunker = SemanticChunker(
+ embedding_model="all-MiniLM-L6-v2",
+ similarity_threshold=0.7,
+ min_chunk_size=100,
+ max_chunk_size=2000
+)
+
+chunks = chunker.chunk(long_text)
+
+for chunk in chunks:
+ print(f"Chunk: {chunk.text[:100]}...")
+ print(f"Coherence score: {chunk.metadata.get('coherence_score')}")
+```
+
+---
+
+### EntityAwareChunker
+
+Preserve entity boundaries during chunking for GraphRAG.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `chunk(text, entities)` | Chunk preserving entities | Entity boundary detection |
+| `extract_entities(text)` | Extract entities | NER extraction |
+| `find_safe_split_points(text, entities)` | Find split points | Entity span checking |
+
+**Example:**
+
+```python
+from semantica.split import EntityAwareChunker
+from semantica.semantic_extract import NERExtractor
+
+# Extract entities first
+ner = NERExtractor(method="llm")
+entities = ner.extract(text)
+
+# Chunk preserving entities
+chunker = EntityAwareChunker(
+ chunk_size=1000,
+ chunk_overlap=200,
+ ner_method="llm"
+)
+
+chunks = chunker.chunk(text, entities=entities)
+
+for chunk in chunks:
+ print(f"Entities in chunk: {chunk.metadata.get('entities')}")
+```
+
+---
+
+### RelationAwareChunker
+
+Preserve relationship triples during chunking.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `chunk(text, relationships)` | Chunk preserving triples | Triple span tracking |
+| `extract_relationships(text)` | Extract relationships | Relation extraction |
+| `validate_triple_integrity(chunk, relationships)` | Validate triples | Integrity checking |
+
+**Example:**
+
+```python
+from semantica.split import RelationAwareChunker
+from semantica.semantic_extract import RelationExtractor
+
+# Extract relationships
+rel_extractor = RelationExtractor()
+relationships = rel_extractor.extract(text)
+
+# Chunk preserving relationships
+chunker = RelationAwareChunker(
+ chunk_size=1000,
+ preserve_triples=True
+)
+
+chunks = chunker.chunk(text, relationships=relationships)
+
+for chunk in chunks:
+ print(f"Relationships: {chunk.metadata.get('relationships')}")
+```
+
+---
+
+### GraphBasedChunker
+
+Chunk based on graph structure and centrality.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `chunk(text, graph)` | Chunk by graph structure | Centrality-based |
+| `calculate_centrality(graph)` | Calculate node centrality | Degree/betweenness/closeness |
+| `detect_communities(graph)` | Detect communities | Louvain/Leiden algorithm |
+
+**Example:**
+
+```python
+from semantica.split import GraphBasedChunker
+from semantica.kg import GraphBuilder
+
+# Build graph
+builder = GraphBuilder()
+kg = builder.build(entities, relationships)
+
+# Chunk by graph structure
+chunker = GraphBasedChunker(
+ centrality_method="betweenness",
+ community_algorithm="louvain"
+)
+
+chunks = chunker.chunk(text, graph=kg)
+
+for chunk in chunks:
+ print(f"Community: {chunk.metadata.get('community_id')}")
+ print(f"Centrality: {chunk.metadata.get('avg_centrality')}")
+```
+
+---
+
+### StructuralChunker
+
+Structure-aware chunking respecting document hierarchy.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `chunk(text)` | Chunk by structure | Heading/section detection |
+| `detect_structure(text)` | Detect document structure | Markdown/HTML parsing |
+| `build_hierarchy(sections)` | Build section hierarchy | Tree construction |
+
+**Example:**
+
+```python
+from semantica.split import StructuralChunker
+
+chunker = StructuralChunker(
+ respect_headings=True,
+ respect_paragraphs=True,
+ respect_lists=True,
+ max_chunk_size=2000
+)
+
+chunks = chunker.chunk(markdown_text)
+
+for chunk in chunks:
+ print(f"Section: {chunk.metadata.get('section_title')}")
+ print(f"Level: {chunk.metadata.get('heading_level')}")
+```
+
+---
+
+### HierarchicalChunker
+
+Multi-level hierarchical chunking.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `chunk(text)` | Multi-level chunking | Recursive hierarchical split |
+| `create_hierarchy(chunks)` | Create chunk hierarchy | Tree structure |
+
+**Example:**
+
+```python
+from semantica.split import HierarchicalChunker
+
+chunker = HierarchicalChunker(
+ chunk_sizes=[2000, 1000, 500],
+ chunk_overlaps=[400, 200, 100],
+ create_parent_chunks=True
+)
+
+chunks = chunker.chunk(long_text)
+
+for chunk in chunks:
+ print(f"Level: {chunk.metadata.get('level')}")
+ print(f"Parent: {chunk.metadata.get('parent_id')}")
+ print(f"Children: {chunk.metadata.get('child_ids')}")
+```
+
+---
+
+### ChunkValidator
+
+Validate chunk quality and completeness.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `validate(chunks)` | Validate chunks | Multi-factor validation |
+| `check_size(chunk)` | Check size constraints | Min/max checking |
+| `check_overlap(chunks)` | Check overlap | Overlap calculation |
+| `check_completeness(chunks, original)` | Check coverage | Coverage verification |
+| `calculate_quality_score(chunk)` | Quality score | Multi-factor scoring |
+
+**Example:**
+
+```python
+from semantica.split import ChunkValidator
+
+validator = ChunkValidator(
+ min_chunk_size=100,
+ max_chunk_size=2000,
+ min_overlap=50,
+ max_overlap=500
+)
+
+validation_result = validator.validate(chunks)
+
+print(f"Valid: {validation_result['valid']}")
+print(f"Issues: {validation_result['issues']}")
+print(f"Quality score: {validation_result['quality_score']}")
+```
+
+---
+
+### ProvenanceTracker
+
+Track chunk provenance for data lineage.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `track(chunk, source)` | Track chunk origin | Provenance recording |
+| `get_lineage(chunk_id)` | Get chunk lineage | Lineage retrieval |
+| `visualize_lineage(chunk_id)` | Visualize lineage | Graph visualization |
+
+**Example:**
+
+```python
+from semantica.split import ProvenanceTracker
+
+tracker = ProvenanceTracker()
+
+for chunk in chunks:
+ tracker.track(
+ chunk=chunk,
+ source={
+ "document_id": "doc123",
+ "file_path": "data/document.pdf",
+ "page": 5,
+ "timestamp": "2024-01-01T00:00:00Z"
+ }
+ )
+
+# Get lineage
+lineage = tracker.get_lineage(chunk.id)
+print(f"Source: {lineage['source']}")
+print(f"Transformations: {lineage['transformations']}")
+```
+
+---
+
+## Convenience Functions
+
+Quick access to splitting operations:
+
+```python
+from semantica.split import (
+ split_recursive,
+ split_by_tokens,
+ split_by_sentences,
+ split_by_paragraphs,
+ split_entity_aware,
+ split_relation_aware,
+ split_semantic_transformer,
+ list_available_methods
+)
+
+# List available methods
+methods = list_available_methods()
+print(f"Available methods: {methods}")
+
+# Quick splitting
+chunks = split_recursive(text, chunk_size=1000, chunk_overlap=200)
+chunks = split_by_sentences(text, sentences_per_chunk=5)
+chunks = split_entity_aware(text, ner_method="llm")
+```
+
+---
+
+## Configuration
+
+### Environment Variables
+
+```bash
+# Default settings
+export SPLIT_DEFAULT_METHOD=recursive
+export SPLIT_DEFAULT_CHUNK_SIZE=1000
+export SPLIT_DEFAULT_CHUNK_OVERLAP=200
+
+# Semantic chunking
+export SPLIT_EMBEDDING_MODEL=all-MiniLM-L6-v2
+export SPLIT_SIMILARITY_THRESHOLD=0.7
+
+# Entity-aware
+export SPLIT_NER_METHOD=spacy
+export SPLIT_PRESERVE_ENTITIES=true
+
+# LLM-based
+export SPLIT_LLM_PROVIDER=openai
+export SPLIT_LLM_MODEL=gpt-4
+```
+
+### YAML Configuration
+
+```yaml
+# config.yaml - Split Module Configuration
+
+split:
+ default_method: recursive
+ chunk_size: 1000
+ chunk_overlap: 200
+
+ recursive:
+ separators: ["\n\n", "\n", " ", ""]
+ keep_separator: true
+
+ semantic:
+ embedding_model: all-MiniLM-L6-v2
+ similarity_threshold: 0.7
+ min_chunk_size: 100
+ max_chunk_size: 2000
+
+ entity_aware:
+ ner_method: spacy
+ preserve_entities: true
+ min_entity_gap: 50
+
+ relation_aware:
+ preserve_triples: true
+ relation_extraction_method: llm
+
+ graph_based:
+ centrality_method: betweenness
+ community_algorithm: louvain
+ min_community_size: 3
+
+ hierarchical:
+ levels: 3
+ chunk_sizes: [2000, 1000, 500]
+ chunk_overlaps: [400, 200, 100]
+
+ validation:
+ enabled: true
+ min_chunk_size: 100
+ max_chunk_size: 2000
+ check_overlap: true
+ check_completeness: true
+```
+
+---
+
+## Method Comparison
+
+| Method | Best For | Pros | Cons |
+|--------|----------|------|------|
+| **recursive** | General text | Fast, simple | May split mid-sentence |
+| **sentence** | Coherent chunks | Respects sentences | Variable size |
+| **semantic_transformer** | Topic coherence | Semantic boundaries | Slower, needs embeddings |
+| **entity_aware** | GraphRAG | Preserves entities | Requires NER |
+| **relation_aware** | KG extraction | Preserves triples | Requires relation extraction |
+| **graph_based** | Graph analysis | Graph-aware | Requires graph construction |
+| **hierarchical** | Large documents | Multi-level | More complex |
+| **structural** | Formatted docs | Respects structure | Needs structure |
+
+---
+
+## Integration Examples
+
+### Complete GraphRAG Pipeline
+
+```python
+from semantica.split import TextSplitter
+from semantica.semantic_extract import NERExtractor, RelationExtractor
+from semantica.kg import GraphBuilder
+from semantica.embeddings import EmbeddingGenerator
+from semantica.vector_store import VectorStore
+
+# Parse document
+text = "Apple Inc. was founded by Steve Jobs in 1976..."
+
+# Entity-aware chunking
+splitter = TextSplitter(
+ method="entity_aware",
+ ner_method="llm",
+ chunk_size=1000
+)
+chunks = splitter.split(text)
+
+# Extract from each chunk
+ner = NERExtractor(method="llm")
+rel_extractor = RelationExtractor()
+
+all_entities = []
+all_relationships = []
+
+for chunk in chunks:
+ entities = ner.extract(chunk.text)
+ relationships = rel_extractor.extract(chunk.text, entities)
+
+ all_entities.extend(entities)
+ all_relationships.extend(relationships)
+
+# Build knowledge graph
+builder = GraphBuilder()
+kg = builder.build(all_entities, all_relationships)
+
+# Generate embeddings
+embedder = EmbeddingGenerator()
+embeddings = embedder.generate([chunk.text for chunk in chunks])
+
+# Store in vector store
+vector_store = VectorStore()
+vector_store.store(embeddings, chunks)
+```
+
+### Multi-Level Hierarchical Chunking
+
+```python
+from semantica.split import HierarchicalChunker
+
+chunker = HierarchicalChunker(
+ chunk_sizes=[4000, 2000, 1000],
+ chunk_overlaps=[800, 400, 200],
+ create_parent_chunks=True
+)
+
+chunks = chunker.chunk(very_long_document)
+
+# Access hierarchy
+for chunk in chunks:
+ level = chunk.metadata['level']
+ parent_id = chunk.metadata.get('parent_id')
+ child_ids = chunk.metadata.get('child_ids', [])
+
+ print(f"Level {level}: {len(chunk.text)} chars")
+ if parent_id:
+ print(f" Parent: {parent_id}")
+ if child_ids:
+ print(f" Children: {len(child_ids)}")
+```
+
+---
+
+## Best Practices
+
+### 1. Choose Appropriate Chunk Size
+
+```python
+# For semantic search (embeddings)
+splitter = TextSplitter(method="recursive", chunk_size=512)
+
+# For LLM context (GPT-4)
+splitter = TextSplitter(method="recursive", chunk_size=4000)
+
+# For entity extraction
+splitter = TextSplitter(method="entity_aware", chunk_size=1000)
+```
+
+### 2. Use Overlap for Context
+
+```python
+# 20% overlap recommended
+splitter = TextSplitter(
+ chunk_size=1000,
+ chunk_overlap=200 # 20%
+)
+```
+
+### 3. Validate Chunks
+
+```python
+from semantica.split import ChunkValidator
+
+validator = ChunkValidator()
+validation = validator.validate(chunks)
+
+if not validation['valid']:
+ print(f"Issues: {validation['issues']}")
+```
+
+### 4. Track Provenance
+
+```python
+from semantica.split import ProvenanceTracker
+
+tracker = ProvenanceTracker()
+for chunk in chunks:
+ tracker.track(chunk, source={"doc_id": "123"})
+```
+
+---
+
+## Troubleshooting
+
+### Issue: Chunks too small/large
+
+```python
+# Solution: Adjust chunk size and method
+splitter = TextSplitter(
+ method="recursive",
+ chunk_size=1500, # Increase
+ chunk_overlap=300
+)
+
+# Or use validation
+validator = ChunkValidator(min_chunk_size=500, max_chunk_size=2000)
+```
+
+### Issue: Entities split across chunks
+
+```python
+# Solution: Use entity-aware chunking
+splitter = TextSplitter(
+ method="entity_aware",
+ ner_method="llm",
+ preserve_entities=True
+)
+```
+
+### Issue: Slow semantic chunking
+
+```python
+# Solution: Use faster embedding model or batch processing
+splitter = TextSplitter(
+ method="semantic_transformer",
+ embedding_model="all-MiniLM-L6-v2", # Faster model
+ batch_size=32 # Batch embeddings
+)
+```
+
+---
+
+## Performance Tips
+
+### Memory Optimization
+
+```python
+# Process in batches
+def chunk_large_corpus(documents, batch_size=100):
+ splitter = TextSplitter(method="recursive")
+
+ for i in range(0, len(documents), batch_size):
+ batch = documents[i:i + batch_size]
+ chunks = splitter.split_documents(batch)
+ yield from chunks
+```
+
+### Speed Optimization
+
+```python
+# Use faster methods for large documents
+splitter = TextSplitter(
+ method="recursive", # Fastest
+ chunk_size=1000
+)
+
+# Avoid LLM-based for large corpora
+# Use semantic_transformer instead of llm
+```
+
+---
+
+## See Also
+
+- [Parse Module](parse.md) - Document parsing
+- [Semantic Extract Module](semantic_extract.md) - Entity extraction
+- [Knowledge Graph Module](kg.md) - Graph construction
+- [Embeddings Module](embeddings.md) - Vector generation
+- [Vector Store Module](vector_store.md) - Vector storage
diff --git a/docs/reference/triple_store.md b/docs/reference/triple_store.md
index dad5b708..bf12f861 100644
--- a/docs/reference/triple_store.md
+++ b/docs/reference/triple_store.md
@@ -1,114 +1,876 @@
-# Triple Store Module
+# Triple Store
-Store and query RDF triples with support for SPARQL queries and semantic reasoning using industry-standard triple stores.
+> **Store and query RDF triples with SPARQL support and semantic reasoning using industry-standard triple stores.**
-## Overview
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-graph-outline:{ .lg .middle } **RDF Storage**
+
+ ---
+
+ Store subject-predicate-object triples in W3C-compliant RDF format
+
+- :material-code-braces:{ .lg .middle } **SPARQL Queries**
+
+ ---
+
+ Full W3C SPARQL 1.1 query language support for powerful semantic queries
+
+- :material-brain:{ .lg .middle } **Reasoning**
+
+ ---
+
+ RDFS and OWL reasoning for inference and knowledge discovery
+
+- :material-database-sync:{ .lg .middle } **Multiple Backends**
+
+ ---
+
+ Blazegraph, Apache Jena, RDF4J, and Virtuoso support
+
+- :material-link-variant:{ .lg .middle } **Federation**
-- **RDF Storage**: Store subject-predicate-object triples
-- **SPARQL Queries**: W3C-compliant query language
-- **Reasoning**: RDFS and OWL reasoning
-- **Multiple Backends**: RDFLib, Jena, Virtuoso, GraphDB
-- **Federation**: Query across multiple triple stores
+ ---
+
+ Query across multiple triple stores with SPARQL federation
+
+- :material-upload-multiple:{ .lg .middle } **Bulk Loading**
+
+ ---
+
+ High-performance bulk data loading with progress tracking
+
+</div>
+
+!!! tip "Choosing the Right Backend"
+ - **Blazegraph**: High-performance, excellent for large datasets, GPU acceleration
+ - **Apache Jena**: Full-featured, TDB2 storage, SHACL validation
+ - **RDF4J**: Java-based, excellent tooling, multiple storage backends
+ - **Virtuoso**: Enterprise-grade, excellent performance, SQL integration
---
-## Algorithms Used
+## ⚙️ Algorithms Used
### Query Algorithms
- **SPARQL Query Optimization**: Join reordering with selectivity estimation
- **Triple Pattern Matching**: Index-based lookup with B+ trees
-- **Graph Pattern Matching**: Subgraph isomorphism
-- **Query Planning**: Cost-based optimization
+- **Graph Pattern Matching**: Subgraph isomorphism with backtracking
+- **Query Planning**: Cost-based optimization with statistics
+- **Join Algorithms**: Hash join, merge join, nested loop join
+- **Filter Pushdown**: Early filter application for performance
### Indexing
-- **SPO Index**: Subject-Predicate-Object index
-- **POS Index**: Predicate-Object-Subject index
-- **OSP Index**: Object-Subject-Predicate index
-- **Six-Index Scheme**: All permutations for optimal query performance
+- **SPO Index**: Subject-Predicate-Object index for subject lookups
+- **POS Index**: Predicate-Object-Subject index for predicate lookups
+- **OSP Index**: Object-Subject-Predicate index for object lookups
+- **Six-Index Scheme**: All permutations (SPO, SOP, PSO, POS, OSP, OPS) for optimal query performance
+- **B+ Tree Indexing**: Efficient range queries and sorted access
+- **Hash Indexing**: O(1) exact match lookups
+
+### Reasoning Algorithms
+- **RDFS Reasoning**: Subclass/subproperty inference, domain/range inference
+- **OWL Reasoning**: Class hierarchy, property characteristics, cardinality constraints
+- **Forward Chaining**: Materialization of inferred triples
+- **Backward Chaining**: On-demand inference during query execution
+- **Rule-Based Inference**: Custom SWRL rules
+
+### Bulk Loading
+- **Batch Processing**: Chunked triple insertion with configurable batch size
+- **Parallel Loading**: Multi-threaded data loading
+- **Index Building**: Deferred index construction for faster loading
+- **Transaction Management**: Atomic batch commits with rollback support
---
## Main Classes
-### TripleStore
+### TripleManager
+Main coordinator for triple store operations across multiple backends.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `add_triple(subject, predicate, object)` | Add single triple | Index insertion |
-| `add_triples(triples)` | Batch add triples | Bulk index insertion |
-| `query(sparql_query)` | Execute SPARQL query | Query optimization + execution |
-| `delete(pattern)` | Delete matching triples | Pattern matching + deletion |
-| `serialize(format)` | Serialize to RDF format | Format-specific serialization |
+| `register_store(id, backend, endpoint)` | Register triple store | Store registration |
+| `add_triple(triple, store_id)` | Add single triple | Index insertion |
+| `add_triples(triples, store_id)` | Batch add triples | Bulk index insertion |
+| `query(sparql, store_id)` | Execute SPARQL query | Query optimization + execution |
+| `delete(pattern, store_id)` | Delete matching triples | Pattern matching + deletion |
+| `bulk_load(file_path, format, store_id)` | Bulk load from file | Streaming parser + batch insert |
+| `get_stats(store_id)` | Get store statistics | Statistics collection |
**Example:**
```python
-from semantica.triple_store import TripleStore
+from semantica.triple_store import TripleManager
-store = TripleStore(backend="rdflib")
+# Initialize manager
+manager = TripleManager()
-# Add triples
-store.add_triple(
- subject="http://example.org/AppleInc",
- predicate="http://example.org/foundedBy",
- object="http://example.org/SteveJobs"
+# Register Blazegraph store
+store = manager.register_store(
+ store_id="main",
+ backend="blazegraph",
+ endpoint="http://localhost:9999/blazegraph/sparql"
)
-# SPARQL query
-results = store.query("""
- SELECT ?company ?founder WHERE {
- ?company <http://example.org/foundedBy> ?founder .
+# Add single triple
+result = manager.add_triple(
+ triple={
+ "subject": "http://example.org/Alice",
+ "predicate": "http://example.org/knows",
+ "object": "http://example.org/Bob"
+ },
+ store_id="main"
+)
+
+# Add multiple triples
+triples = [
+ {
+ "subject": "http://example.org/Alice",
+ "predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
+ "object": "http://example.org/Person"
+ },
+ {
+ "subject": "http://example.org/Bob",
+ "predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
+ "object": "http://example.org/Person"
}
-""")
+]
+
+manager.add_triples(triples, store_id="main")
+
+# Query with SPARQL
+results = manager.query("""
+ PREFIX ex: <http://example.org/>
+ PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
+
+ SELECT ?person ?friend WHERE {
+ ?person rdf:type ex:Person .
+ ?person ex:knows ?friend .
+ }
+""", store_id="main")
+
+for row in results["results"]["bindings"]:
+ print(f"{row['person']['value']} knows {row['friend']['value']}")
-for row in results:
- print(f"{row['company']} founded by {row['founder']}")
+# Get statistics
+stats = manager.get_stats("main")
+print(f"Total triples: {stats['triple_count']}")
```
---
-### SPARQLQueryEngine
+### QueryEngine
+SPARQL query execution and optimization engine.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `execute(query)` | Execute SPARQL query | Parse + optimize + execute |
+| `execute(query, store)` | Execute SPARQL query | Parse + optimize + execute |
| `parse_query(sparql)` | Parse SPARQL syntax | SPARQL parser |
-| `optimize_query(query)` | Optimize query plan | Join reordering |
+| `optimize_query(query)` | Optimize query plan | Join reordering + filter pushdown |
| `explain_query(query)` | Explain query plan | Query plan visualization |
+| `validate_query(sparql)` | Validate SPARQL syntax | Syntax validation |
**SPARQL Query Types:**
-- **SELECT**: Retrieve variable bindings
-- **CONSTRUCT**: Build RDF graph
-- **ASK**: Boolean query
-- **DESCRIBE**: Describe resources
+
+| Query Type | Description | Use Case |
+|------------|-------------|----------|
+| **SELECT** | Retrieve variable bindings | Data retrieval |
+| **CONSTRUCT** | Build RDF graph | Graph transformation |
+| **ASK** | Boolean query | Existence check |
+| **DESCRIBE** | Describe resources | Resource exploration |
+
+**Example:**
+
+```python
+from semantica.triple_store import QueryEngine, TripleManager
+
+manager = TripleManager()
+store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
+
+engine = QueryEngine()
+
+# SELECT query
+select_query = """
+ PREFIX ex: <http://example.org/>
+ SELECT ?name ?age WHERE {
+ ?person ex:name ?name .
+ ?person ex:age ?age .
+ FILTER (?age > 18)
+ }
+ ORDER BY DESC(?age)
+ LIMIT 10
+"""
+
+results = engine.execute(select_query, store)
+
+# CONSTRUCT query
+construct_query = """
+ PREFIX ex: <http://example.org/>
+ CONSTRUCT {
+ ?person ex:isAdult true .
+ }
+ WHERE {
+ ?person ex:age ?age .
+ FILTER (?age >= 18)
+ }
+"""
+
+graph = engine.execute(construct_query, store)
+
+# ASK query
+ask_query = """
+ PREFIX ex: <http://example.org/>
+ ASK {
+ ?person ex:name "Alice" .
+ }
+"""
+
+exists = engine.execute(ask_query, store)
+print(f"Alice exists: {exists}")
+
+# Explain query plan
+plan = engine.explain_query(select_query)
+print(f"Query plan: {plan}")
+```
+
+---
+
+### BulkLoader
+
+High-performance bulk data loading with progress tracking.
+
+**Methods:**
+
+| Method | Description | Algorithm |
+|--------|-------------|-----------|
+| `load(file_path, format, store)` | Load RDF file | Streaming parser + batch insert |
+| `load_from_url(url, format, store)` | Load from URL | HTTP streaming + batch insert |
+| `load_from_string(data, format, store)` | Load from string | String parser + batch insert |
+| `get_progress()` | Get loading progress | Progress tracking |
+
+**Supported Formats:**
+- **RDF/XML**: W3C RDF/XML format
+- **Turtle**: Terse RDF Triple Language
+- **N-Triples**: Line-based triple format
+- **N-Quads**: N-Triples with named graphs
+- **JSON-LD**: JSON-based RDF format
+- **TriG**: Turtle with named graphs
+
+**Example:**
+
+```python
+from semantica.triple_store import BulkLoader, TripleManager
+
+manager = TripleManager()
+store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
+
+loader = BulkLoader(
+ batch_size=10000,
+ show_progress=True,
+ parallel=True,
+ n_jobs=4
+)
+
+# Load from file
+progress = loader.load(
+ file_path="knowledge_graph.ttl",
+ format="turtle",
+ store=store
+)
+
+print(f"Loaded {progress['triples_loaded']} triples in {progress['elapsed_time']:.2f}s")
+print(f"Throughput: {progress['triples_per_second']:.0f} triples/sec")
+
+# Load from URL
+progress = loader.load_from_url(
+ url="https://example.org/data.rdf",
+ format="rdf/xml",
+ store=store
+)
+
+# Load from string
+rdf_data = """
+@prefix ex: <http://example.org/> .
+@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
+
+ex:Alice rdf:type ex:Person ;
+ ex:name "Alice" ;
+ ex:age 30 .
+"""
+
+progress = loader.load_from_string(
+ data=rdf_data,
+ format="turtle",
+ store=store
+)
+```
+
+---
+
+### Backend Adapters
+
+#### BlazegraphAdapter
+
+High-performance triple store with GPU acceleration support.
+
+**Features:**
+- High-performance SPARQL query execution
+- GPU acceleration for analytics
+- Full-text search integration
+- Geospatial query support
+- High availability clustering
+
+**Example:**
+
+```python
+from semantica.triple_store import BlazegraphAdapter
+
+adapter = BlazegraphAdapter(
+ endpoint="http://localhost:9999/blazegraph/sparql",
+ namespace="kb", # Blazegraph namespace
+ timeout=30
+)
+
+adapter.connect()
+
+# Create namespace
+adapter.create_namespace("my_kb", properties={
+ "com.bigdata.rdf.store.AbstractTripleStore.textIndex": "true",
+ "com.bigdata.rdf.store.AbstractTripleStore.geoSpatial": "true"
+})
+
+# Add triples
+adapter.add_triple(
+ subject="http://example.org/Alice",
+ predicate="http://example.org/name",
+ object_literal="Alice",
+ object_datatype="http://www.w3.org/2001/XMLSchema#string"
+)
+
+# Full-text search
+results = adapter.query("""
+ PREFIX bds: <http://www.bigdata.com/rdf/search#>
+ SELECT ?subject ?score WHERE {
+ ?subject bds:search "machine learning" .
+ ?subject bds:relevance ?score .
+ }
+ ORDER BY DESC(?score)
+""")
+```
+
+---
+
+#### JenaAdapter
+
+Full-featured RDF framework with TDB2 storage.
+
+**Features:**
+- TDB2 native triple store
+- SHACL validation
+- Inference engines (RDFS, OWL)
+- Fuseki SPARQL server
+- RDF/XML, Turtle, JSON-LD support
+
+**Example:**
+
+```python
+from semantica.triple_store import JenaAdapter
+
+adapter = JenaAdapter(
+ tdb_directory="./tdb2_data",
+ inference="rdfs" # rdfs, owl, or None
+)
+
+adapter.connect()
+
+# Add triples with inference
+adapter.add_triple(
+ subject="http://example.org/Dog",
+ predicate="http://www.w3.org/2000/01/rdf-schema#subClassOf",
+ object="http://example.org/Animal"
+)
+
+adapter.add_triple(
+ subject="http://example.org/Fido",
+ predicate="http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
+ object="http://example.org/Dog"
+)
+
+# Query with inference (Fido is inferred to be an Animal)
+results = adapter.query("""
+ PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
+ PREFIX ex: <http://example.org/>
+
+ SELECT ?animal WHERE {
+ ?animal rdf:type ex:Animal .
+ }
+""")
+
+# SHACL validation
+shapes = """
+@prefix sh: <http://www.w3.org/ns/shacl#> .
+@prefix ex: <http://example.org/> .
+
+ex:PersonShape a sh:NodeShape ;
+ sh:targetClass ex:Person ;
+ sh:property [
+ sh:path ex:name ;
+ sh:minCount 1 ;
+ sh:datatype xsd:string ;
+ ] .
+"""
+
+validation_report = adapter.validate_shacl(shapes)
+print(f"Valid: {validation_report['conforms']}")
+```
+
+---
+
+## Convenience Functions
+
+Quick access to triple store operations:
+
+```python
+from semantica.triple_store import (
+ add_triple,
+ add_triples,
+ execute_query,
+ bulk_load,
+ export_graph,
+ import_graph
+)
+
+# Add single triple
+add_triple(
+ subject="http://example.org/Alice",
+ predicate="http://example.org/knows",
+ object="http://example.org/Bob"
+)
+
+# Execute SPARQL query
+results = execute_query("""
+ SELECT ?s ?p ?o WHERE {
+ ?s ?p ?o .
+ }
+ LIMIT 10
+""")
+
+# Bulk load
+progress = bulk_load(
+ file_path="data.ttl",
+ format="turtle",
+ batch_size=10000
+)
+
+# Export graph
+export_graph(
+ output_path="export.rdf",
+ format="rdf/xml"
+)
+```
---
## Configuration
+### Environment Variables
+
+```bash
+# General settings
+export TRIPLE_STORE_DEFAULT_BACKEND=blazegraph
+export TRIPLE_STORE_BATCH_SIZE=10000
+export TRIPLE_STORE_TIMEOUT=30
+
+# Blazegraph settings
+export TRIPLE_STORE_BLAZEGRAPH_ENDPOINT=http://localhost:9999/blazegraph/sparql
+export TRIPLE_STORE_BLAZEGRAPH_NAMESPACE=kb
+
+# Jena settings
+export TRIPLE_STORE_JENA_TDB_DIRECTORY=./tdb2_data
+export TRIPLE_STORE_JENA_INFERENCE=rdfs
+
+# RDF4J settings
+export TRIPLE_STORE_RDF4J_SERVER_URL=http://localhost:8080/rdf4j-server
+export TRIPLE_STORE_RDF4J_REPOSITORY_ID=my_repo
+
+# Virtuoso settings
+export TRIPLE_STORE_VIRTUOSO_HOST=localhost
+export TRIPLE_STORE_VIRTUOSO_PORT=1111
+export TRIPLE_STORE_VIRTUOSO_USER=dba
+export TRIPLE_STORE_VIRTUOSO_PASSWORD=dba
+```
+
+### YAML Configuration
+
```yaml
# config.yaml - Triple Store Configuration
triple_store:
- backend: rdflib # rdflib, jena, virtuoso, graphdb
+ backend: blazegraph # blazegraph, jena, rdf4j, virtuoso
+ batch_size: 10000
+ timeout: 30
+ enable_reasoning: true
- indexing:
- schemes: [SPO, POS, OSP] # Index permutations
+ blazegraph:
+ endpoint: http://localhost:9999/blazegraph/sparql
+ namespace: kb
+ properties:
+ textIndex: true
+ geoSpatial: false
+
+ jena:
+ tdb_directory: ./tdb2_data
+ inference: rdfs # rdfs, owl, none
+ unionDefaultGraph: true
+
+ rdf4j:
+ server_url: http://localhost:8080/rdf4j-server
+ repository_id: my_repo
+
+ virtuoso:
+ host: localhost
+ port: 1111
+ user: dba
+ password: dba
+ graph_uri: http://example.org/graph
query:
optimize: true
- timeout: 30 # seconds
+ cache_enabled: true
+ cache_size: 1000
+ explain_plans: false
+```
+
+---
+
+## Backend Comparison
+
+| Feature | Blazegraph | Apache Jena | RDF4J | Virtuoso |
+|---------|------------|-------------|-------|----------|
+| **Performance** | Excellent | Good | Good | Excellent |
+| **Scalability** | High | Medium | Medium | Very High |
+| **SPARQL 1.1** | Full | Full | Full | Full |
+| **Reasoning** | Limited | Full (RDFS/OWL) | Full | Full |
+| **Full-Text** | Yes | Yes | Yes | Yes |
+| **Geospatial** | Yes | Limited | Limited | Yes |
+| **Clustering** | Yes | No | No | Yes |
+| **License** | GPLv2 | Apache 2.0 | BSD | Commercial/GPL |
+| **Best For** | Large datasets | Java apps | Java apps | Enterprise |
+
+---
+
+## Docker Quick Start
+
+### Blazegraph
+
+```bash
+docker run -d -p 9999:9999 \
+ -v ./blazegraph-data:/data \
+ --name blazegraph \
+ lyrasis/blazegraph:2.1.5
+
+# Access UI at http://localhost:9999/blazegraph
+```
+
+### Apache Jena Fuseki
+
+```bash
+docker run -d -p 3030:3030 \
+ -v ./fuseki-data:/fuseki \
+ --name fuseki \
+ stain/jena-fuseki
+
+# Access UI at http://localhost:3030
+```
+
+### RDF4J Server
+
+```bash
+docker run -d -p 8080:8080 \
+ -v ./rdf4j-data:/var/rdf4j \
+ --name rdf4j \
+ eclipse/rdf4j-workbench
+
+# Access UI at http://localhost:8080/rdf4j-workbench
+```
+
+---
+
+## Advanced SPARQL Examples
+
+### Aggregation Queries
+
+```sparql
+PREFIX ex: <http://example.org/>
+
+SELECT ?department (COUNT(?employee) as ?count) (AVG(?salary) as ?avg_salary)
+WHERE {
+ ?employee ex:worksIn ?department .
+ ?employee ex:salary ?salary .
+}
+GROUP BY ?department
+HAVING (COUNT(?employee) > 5)
+ORDER BY DESC(?count)
+```
+
+### Property Paths
+
+```sparql
+PREFIX ex: <http://example.org/>
+
+# Find all ancestors (transitive closure)
+SELECT ?person ?ancestor
+WHERE {
+ ?person ex:hasParent+ ?ancestor .
+}
+
+# Find friends of friends
+SELECT ?person ?friend_of_friend
+WHERE {
+ ?person ex:knows/ex:knows ?friend_of_friend .
+ FILTER (?person != ?friend_of_friend)
+}
+```
+
+### Federated Queries
+
+```sparql
+PREFIX ex: <http://example.org/>
+
+SELECT ?person ?company ?stock_price
+WHERE {
+ # Local store
+ ?person ex:worksFor ?company .
+
+ # Remote store
+ SERVICE <http://remote-store.example.org/sparql> {
+ ?company ex:stockPrice ?stock_price .
+ }
+}
+```
+
+### Update Operations
+
+```sparql
+PREFIX ex: <http://example.org/>
+
+# INSERT DATA
+INSERT DATA {
+ ex:Alice ex:knows ex:Bob .
+ ex:Bob ex:knows ex:Charlie .
+}
+
+# DELETE/INSERT
+DELETE {
+ ?person ex:age ?old_age .
+}
+INSERT {
+ ?person ex:age ?new_age .
+}
+WHERE {
+ ?person ex:age ?old_age .
+ BIND(?old_age + 1 AS ?new_age)
+}
+```
+
+---
+
+## Performance Tips
+
+### Query Optimization
+
+```python
+# Use LIMIT for large result sets
+query = """
+ SELECT ?s ?p ?o WHERE {
+ ?s ?p ?o .
+ }
+ LIMIT 1000
+"""
+
+# Use FILTER efficiently (after other patterns)
+query = """
+ SELECT ?person ?name WHERE {
+ ?person rdf:type ex:Person .
+ ?person ex:name ?name .
+ FILTER (STRLEN(?name) > 5) # Filter after pattern matching
+ }
+"""
+
+# Use property paths wisely
+query = """
+ SELECT ?person ?ancestor WHERE {
+ ?person ex:hasParent{1,3} ?ancestor . # Limit path length
+ }
+"""
+```
+
+### Bulk Loading Optimization
+
+```python
+from semantica.triple_store import BulkLoader
+
+loader = BulkLoader(
+ batch_size=50000, # Larger batches for better performance
+ parallel=True, # Enable parallel loading
+ n_jobs=8, # Use multiple cores
+ disable_indexes=True, # Disable indexes during load
+ rebuild_indexes=True # Rebuild after load
+)
+
+progress = loader.load("large_dataset.nt", format="ntriples")
+```
+
+### Indexing Strategy
+
+```python
+# Create selective indexes
+adapter.create_index("predicate", ["http://example.org/name"])
+adapter.create_index("object", ["http://example.org/Person"])
+
+# Full-text index for specific predicates
+adapter.create_fulltext_index([
+ "http://example.org/description",
+ "http://example.org/content"
+])
+```
+
+---
+
+## Integration Examples
+
+### Knowledge Graph Export to RDF
+
+```python
+from semantica.kg import GraphBuilder
+from semantica.triple_store import TripleManager, BulkLoader
+
+# Build knowledge graph
+builder = GraphBuilder()
+kg = builder.build(entities, relationships)
+
+# Convert to RDF triples
+triples = []
+for entity in kg.entities:
+ triples.append({
+ "subject": f"http://example.org/{entity.id}",
+ "predicate": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
+ "object": f"http://example.org/{entity.type}"
+ })
+
+ for prop, value in entity.properties.items():
+ triples.append({
+ "subject": f"http://example.org/{entity.id}",
+ "predicate": f"http://example.org/{prop}",
+ "object_literal": str(value)
+ })
+
+# Load into triple store
+manager = TripleManager()
+store = manager.register_store("main", "blazegraph", "http://localhost:9999/blazegraph/sparql")
+manager.add_triples(triples, store_id="main")
+```
+
+### Semantic Search with SPARQL
+
+```python
+from semantica.triple_store import QueryEngine
+
+engine = QueryEngine()
+
+def semantic_search(keywords, limit=10):
+ query = f"""
+ PREFIX ex: <http://example.org/>
+ PREFIX bds: <http://www.bigdata.com/rdf/search#>
+
+ SELECT ?doc ?title ?score WHERE {{
+ ?doc bds:search "{keywords}" .
+ ?doc bds:relevance ?score .
+ ?doc ex:title ?title .
+ }}
+ ORDER BY DESC(?score)
+ LIMIT {limit}
+ """
+
+ return engine.execute(query, store)
+
+results = semantic_search("machine learning", limit=5)
+```
+
+---
+
+## Troubleshooting
+
+### Common Issues
+
+**Issue**: Slow query performance
+
+```python
+# Solution 1: Add indexes
+adapter.create_index("predicate", ["http://example.org/knows"])
+
+# Solution 2: Optimize query
+# Bad: Cartesian product
+query_bad = """
+ SELECT ?s ?o WHERE {
+ ?s ?p1 ?o1 .
+ ?o ?p2 ?o2 .
+ }
+"""
+
+# Good: Constrained join
+query_good = """
+ SELECT ?s ?o WHERE {
+ ?s ex:knows ?o .
+ ?o rdf:type ex:Person .
+ }
+"""
+
+# Solution 3: Use LIMIT
+results = execute_query(query + " LIMIT 1000")
+```
+
+**Issue**: Out of memory during bulk load
+
+```python
+# Solution: Use streaming and smaller batches
+loader = BulkLoader(
+ batch_size=10000, # Smaller batches
+ streaming=True, # Stream from file
+ clear_cache=True # Clear cache between batches
+)
+```
+
+**Issue**: SPARQL syntax errors
+
+```python
+# Solution: Validate query first
+from semantica.triple_store import QueryEngine
+
+engine = QueryEngine()
+is_valid = engine.validate_query(sparql_query)
+
+if not is_valid:
+ errors = engine.get_syntax_errors(sparql_query)
+ print(f"Syntax errors: {errors}")
```
---
## See Also
-- [Knowledge Graph Module](kg.md)
-- [Ontology Module](ontology.md)
+- [Knowledge Graph Module](kg.md) - Build and analyze knowledge graphs
+- [Ontology Module](ontology.md) - Ontology generation and management
+- [Graph Store Module](graph_store.md) - Property graph storage
+- [Export Module](export.md) - Export to various formats
diff --git a/docs/reference/utils.md b/docs/reference/utils.md
index 027b5632..21fc4fc6 100644
--- a/docs/reference/utils.md
+++ b/docs/reference/utils.md
@@ -1,180 +1,187 @@
-# Utils Module
+# Utils
-Utility functions and helper classes for common operations including file handling, text processing, and data manipulation.
+> **Shared utilities for logging, validation, error handling, and common operations.**
-## Overview
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-console-line:{ .lg .middle } **Logging**
+
+ ---
+
+ Structured logging with performance tracking and error reporting
+
+- :material-alert-circle-outline:{ .lg .middle } **Error Handling**
+
+ ---
+
+ Custom exception hierarchy and error formatting
+
+- :material-check-all:{ .lg .middle } **Validation**
+
+ ---
+
+ Data validation for entities, relationships, and configuration
+
+- :material-progress-clock:{ .lg .middle } **Progress Tracking**
+
+ ---
+
+ Track long-running operations with console or file output
+
+- :material-tools:{ .lg .middle } **Helpers**
+
+ ---
+
+ Common functions for text cleaning, hashing, and file I/O
+
+- :material-code-json:{ .lg .middle } **Type Definitions**
-- **File Operations**: File I/O, path manipulation, compression
-- **Text Utilities**: String manipulation, encoding, hashing
-- **Data Utilities**: JSON/YAML handling, serialization
-- **Logging**: Structured logging with multiple handlers
-- **Validation**: Schema validation, type checking
+ ---
+
+ Shared TypedDicts and Enums for type safety
+
+</div>
+
+!!! tip "When to Use"
+ - **Development**: Use `setup_logging` to configure output.
+ - **Data Cleaning**: Use `clean_text` and `normalize_entities`.
+ - **Validation**: Use `validate_data` before processing external input.
+ - **Debugging**: Use `log_performance` to find bottlenecks.
---
-## Algorithms Used
+## ⚙️ Key Components
-### File Operations
-- **Hashing**: MD5, SHA256 for file integrity checking
-- **Compression**: GZIP, LZMA algorithms for file compression
-- **Chunking**: Fixed-size or sliding window chunking for large files
+### Logging
+- **Structured Output**: JSON or formatted text logs.
+- **Performance Metrics**: Decorators for timing functions.
+- **Quality Logging**: Specialized loggers for data quality issues.
-### Text Processing
-- **Tokenization**: Whitespace and punctuation-based tokenization
-- **Similarity**: Jaccard similarity, Cosine similarity
-- **Hashing**: MurmurHash3 for fast non-cryptographic hashing
+### Validation
+- **Schema Validation**: Check dictionary structure against requirements.
+- **Type Checking**: Runtime type validation.
+- **Constraint Checking**: Numeric ranges, string lengths, regex patterns.
-### Data Serialization
-- **JSON**: Fast JSON encoding/decoding
-- **YAML**: Human-readable configuration format
-- **Pickle**: Python object serialization
+### Progress Tracking
+- **Multi-Environment**: Supports Console (tqdm), Jupyter, and File logging.
+- **Module Awareness**: Tracks progress per module.
---
## Main Classes
-### FileUtils
+### Logger
+Centralized logging configuration.
-**Methods:**
+**Functions:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `list_files(directory, pattern)` | List files matching pattern | Recursive directory traversal |
-| `read_file(path)` | Read file contents | Buffered I/O |
-| `write_file(path, content)` | Write to file | Atomic write with temp file |
-| `hash_file(path, algorithm)` | Calculate file hash | Streaming hash calculation |
-| `compress_file(path, format)` | Compress file | GZIP/LZMA compression |
+| Function | Description |
+|----------|-------------|
+| `setup_logging(level)` | Configure global logging |
+| `get_logger(name)` | Get named logger instance |
+| `log_performance(func)` | Decorator for timing |
**Example:**
```python
-from semantica.utils import FileUtils
+from semantica.utils import setup_logging, get_logger, log_performance
-# List files
-files = FileUtils.list_files(
- directory="documents/",
- pattern="*.pdf",
- recursive=True
-)
+setup_logging(level="INFO")
+logger = get_logger(__name__)
-# Hash file
-file_hash = FileUtils.hash_file("document.pdf", algorithm="sha256")
-print(f"SHA256: {file_hash}")
-
-# Compress file
-FileUtils.compress_file("large_file.json", format="gzip")
+@log_performance
+def process_data(data):
+ logger.info(f"Processing {len(data)} items")
```
----
-
-### TextUtils
+### Validators
+Data validation functions.
-**Methods:**
+**Functions:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `clean_text(text)` | Clean and normalize text | Regex-based cleaning |
-| `tokenize(text, method)` | Tokenize text | Whitespace/punctuation splitting |
-| `calculate_similarity(text1, text2)` | Calculate text similarity | Jaccard or Cosine similarity |
-| `hash_text(text)` | Hash text string | MurmurHash3 |
-| `remove_stopwords(text, language)` | Remove stopwords | Dictionary-based filtering |
+| Function | Description |
+|----------|-------------|
+| `validate_entity(data)` | Check entity structure |
+| `validate_config(cfg)` | Check configuration |
**Example:**
```python
-from semantica.utils import TextUtils
-
-# Clean text
-text = " Hello, World! \n\n "
-cleaned = TextUtils.clean_text(text)
-print(cleaned) # "Hello, World!"
-
-# Calculate similarity
-similarity = TextUtils.calculate_similarity(
- "machine learning",
- "deep learning",
- method="jaccard"
-)
-print(f"Similarity: {similarity:.2f}")
-```
+from semantica.utils import validate_entity, ValidationError
----
+try:
+ validate_entity({"id": "1", "type": "PERSON"})
+except ValidationError as e:
+ print(f"Invalid entity: {e}")
+```
-### DataUtils
+### ProgressTracker
+Tracks execution progress.
-**Methods:**
+**Classes:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `load_json(path)` | Load JSON file | JSON parsing |
-| `save_json(data, path)` | Save to JSON | JSON serialization |
-| `load_yaml(path)` | Load YAML file | YAML parsing |
-| `save_yaml(data, path)` | Save to YAML | YAML serialization |
-| `validate_schema(data, schema)` | Validate against schema | JSON Schema validation |
+| Class | Description |
+|-------|-------------|
+| `ProgressTracker` | Main tracker interface |
+| `ConsoleProgressDisplay` | CLI output |
**Example:**
```python
-from semantica.utils import DataUtils
-
-# Load/save JSON
-data = DataUtils.load_json("config.json")
-DataUtils.save_json(data, "output.json", pretty=True)
+from semantica.utils import track_progress
-# Load/save YAML
-config = DataUtils.load_yaml("config.yaml")
-DataUtils.save_yaml(config, "output.yaml")
-
-# Validate schema
-is_valid = DataUtils.validate_schema(
- data=data,
- schema={"type": "object", "properties": {...}}
-)
+for item in track_progress(items, desc="Processing"):
+ process(item)
```
---
-### LoggerUtils
+## Convenience Functions
+```python
+from semantica.utils import clean_text, hash_data, safe_filename
-**Methods:**
+# Text cleaning
+clean = clean_text(" Hello World ") # "Hello World"
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `get_logger(name)` | Get logger instance | Logger factory |
-| `configure_logging(level, format)` | Configure logging | Handler setup |
+# Hashing
+id = hash_data({"key": "value"})
+
+# File safety
+fname = safe_filename("My File?.txt") # "My_File_.txt"
+```
---
## Configuration
-```yaml
-# config.yaml - Utils Configuration
-
-utils:
- logging:
- level: INFO # DEBUG, INFO, WARNING, ERROR
- format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
- handlers:
- - console
- - file
-
- file:
- default_encoding: utf-8
- buffer_size: 8192
-
- text:
- default_language: en
- remove_stopwords: true
+### Environment Variables
+
+```bash
+export SEMANTICA_LOG_LEVEL=DEBUG
+export SEMANTICA_LOG_FORMAT=json
+export SEMANTICA_PROGRESS_BAR=true
```
---
+## Best Practices
+
+1. **Use `get_logger`**: Always use `get_logger(__name__)` instead of `print` for production code.
+2. **Validate Early**: Validate input data at the boundary (Ingest/Parse) using `validate_data`.
+3. **Handle Exceptions**: Catch `SemanticaError` for framework-specific errors.
+4. **Clean Text**: Use `clean_text` before embedding or extraction to improve quality.
+
+---
+
## See Also
-- [Core Module](core.md) - Framework orchestration
-- [Ingest Module](ingest.md) - Data ingestion
-- [Parse Module](parse.md) - Document parsing
+- [Core Module](core.md) - Uses Utils for infrastructure
+- [Pipeline Module](pipeline.md) - Uses ProgressTracker
diff --git a/docs/reference/vector_store.md b/docs/reference/vector_store.md
index 9f9df327..28f327ea 100644
--- a/docs/reference/vector_store.md
+++ b/docs/reference/vector_store.md
@@ -1,6 +1,6 @@
-# Vector Store Module
+# Vector Store
-> **Store and search vector embeddings with lightning-fast approximate nearest neighbor search.**
+> **Unified vector database interface supporting FAISS, Pinecone, Weaviate, Qdrant, and Milvus with Hybrid Search.**
---
@@ -8,71 +8,69 @@
<div class="grid cards" markdown>
-- :material-database:{ .lg .middle } **Vector Storage**
+- :material-database:{ .lg .middle } **Multi-Backend Support**
---
- Efficient storage of high-dimensional vectors with multiple backend support
+ Seamlessly switch between FAISS (Local), Pinecone, Weaviate, Qdrant, and Milvus
-- :material-magnify:{ .lg .middle } **Similarity Search**
+- :material-magnify-plus:{ .lg .middle } **Hybrid Search**
---
- Fast ANN search with HNSW, IVF, and PQ algorithms
+ Combine dense vector similarity with sparse keyword/metadata filtering
-- :material-merge:{ .lg .middle } **Hybrid Search**
+- :material-filter:{ .lg .middle } **Metadata Filtering**
---
- Combine vector search with keyword/metadata filtering using RRF
+ Rich filtering capabilities (eq, ne, gt, lt, in, contains)
-- :material-cog:{ .lg .middle } **Index Management**
+- :material-layers-triple:{ .lg .middle } **Namespace Isolation**
---
- Multiple index types optimized for different use cases
+ Multi-tenant support via isolated namespaces
-- :material-flash:{ .lg .middle } **Batch Operations**
+- :material-flash:{ .lg .middle } **Performance**
---
- Efficient bulk insert and search with parallel processing
+ Batch operations, index optimization, and caching
-- :material-cloud:{ .lg .middle } **Multiple Backends**
+- :material-cloud-upload:{ .lg .middle } **Cloud & Local**
---
- FAISS, Pinecone, Qdrant, Weaviate, Milvus support
+ Support for both embedded (local) and cloud-native deployments
</div>
-!!! tip "Choosing the Right Index"
- - **Small datasets (<10K)**: Use Flat for exact search
- - **Medium (10K-1M)**: Use IVF or HNSW
- - **Large (>1M)**: Use HNSW with GPU
- - **Memory constrained**: Use PQ for compression
+!!! tip "When to Use"
+ - **Semantic Search**: Finding documents similar to a query
+ - **RAG**: Retrieving context for LLM generation
+ - **Memory**: Storing agent memories as embeddings
+ - **Recommendation**: Finding similar items based on vector proximity
---
## ⚙️ Algorithms Used
-### Indexing Algorithms
-- **Flat (Exact Search)**: Brute-force linear scan, O(n*d) complexity
-- **IVF (Inverted File Index)**: Clustering-based search with k-means, O(√n*d) complexity
-- **HNSW (Hierarchical Navigable Small World)**: Graph-based ANN, O(log n) search complexity
-- **PQ (Product Quantization)**: Compression-based search, reduces memory footprint
-- **LSH (Locality Sensitive Hashing)**: Hash-based approximate search
-
### Similarity Metrics
-- **Cosine Similarity**: `cos(θ) = (A·B) / (||A|| * ||B||)`
-- **Euclidean Distance**: `d = √(Σ(ai - bi)²)`
-- **Dot Product**: `A·B = Σ(ai * bi)`
-- **Manhattan Distance**: `d = Σ|ai - bi|`
+- **Cosine Similarity**: `A · B / ||A|| ||B||` (Default for semantic search)
+- **Euclidean Distance (L2)**: `||A - B||`
+- **Dot Product**: `A · B` (Faster, requires normalized vectors)
+
+### Indexing (FAISS)
+- **Flat**: Exact search (brute force). High accuracy, slow for large datasets.
+- **IVF (Inverted File)**: Partitions space into Voronoi cells. Faster search.
+- **HNSW**: Hierarchical Navigable Small World graphs. Best trade-off for speed/accuracy.
+- **PQ (Product Quantization)**: Compresses vectors for memory efficiency.
-### Hybrid Search Algorithms
-- **RRF (Reciprocal Rank Fusion)**: `score = Σ(1/(k + rank_i))` where k=60
-- **Weighted Combination**: `score = α*vector_score + (1-α)*keyword_score`
-- **Cascade Filtering**: Vector search → metadata filtering → reranking
+### Hybrid Search
+- **Reciprocal Rank Fusion (RRF)**: Combines ranked lists from vector search and keyword search.
+ `Score = 1 / (k + rank_vector) + 1 / (k + rank_keyword)`
+- **Pre-filtering**: Apply metadata filters *before* vector search (supported by most backends).
---
@@ -80,201 +78,154 @@
### VectorStore
+The main facade for all vector operations.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `store(embeddings, documents, metadata)` | Store vectors with metadata | Batch insertion with index building |
-| `search(query_vector, top_k, filters)` | Search similar vectors | ANN search with optional filtering |
-| `delete(ids)` | Delete vectors by ID | Index update with tombstoning |
-| `update(id, vector, metadata)` | Update vector/metadata | In-place update or delete+insert |
-| `create_index(index_type, params)` | Create search index | Index-specific construction algorithm |
-| `rebuild_index()` | Rebuild index from scratch | Full index reconstruction |
-
-**Supported Backends:**
-
-| Backend | Index Types | Best For |
-|---------|-------------|----------|
-| **FAISS** | Flat, IVF, HNSW, PQ | High performance, local deployment |
-| **Pinecone** | Proprietary | Managed cloud service |
-| **Qdrant** | HNSW | Production-ready, filtering support |
-| **Weaviate** | HNSW | GraphQL API, hybrid search |
-| **Milvus** | IVF, HNSW | Distributed, large-scale |
+| Method | Description |
+|--------|-------------|
+| `store_vectors(vectors, metadata)` | Store embeddings |
+| `search(query, k)` | Semantic search |
+| `delete(ids)` | Remove vectors |
**Example:**
```python
from semantica.vector_store import VectorStore
-# Initialize with FAISS backend
-store = VectorStore(
- backend="faiss",
- index_type="HNSW", # Flat, IVF, HNSW, PQ
- metric="cosine", # cosine, euclidean, dot_product
- dimension=1536
-)
+# Initialize (defaults to FAISS)
+store = VectorStore(backend="faiss", dimension=1536)
-# Store embeddings
-store.store(
- embeddings=embeddings,
- documents=documents,
- metadata=[{"source": "doc1.pdf", "page": 1}, ...]
+# Store
+ids = store.store_vectors(
+ vectors=[[0.1, 0.2, ...], ...],
+ metadata=[{"text": "Hello"}, ...]
)
# Search
-results = store.search(
- query_vector=query_embedding,
- top_k=10,
- filters={"source": "doc1.pdf"}
-)
-
-for result in results:
- print(f"Score: {result.score:.3f}, Doc: {result.document}")
+results = store.search(query_vector=[0.1, 0.2, ...], k=5)
```
----
-
### HybridSearch
+Combines vector and metadata search.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `search(query, top_k)` | Hybrid search | Vector + keyword search with RRF fusion |
-| `vector_search(query_vector, top_k)` | Vector-only search | ANN search |
-| `keyword_search(query_text, top_k)` | Keyword-only search | BM25 or TF-IDF |
-| `combine_results(vector_results, keyword_results)` | Merge results | RRF or weighted combination |
-| `rerank(results, query)` | Rerank results | Cross-encoder reranking |
-
-**Reciprocal Rank Fusion (RRF):**
-```
-RRF_score(d) = Σ(1/(k + rank_i(d)))
-where k = 60 (constant), rank_i(d) = rank of document d in result set i
-```
+| Method | Description |
+|--------|-------------|
+| `search(query_vec, filter)` | Execute hybrid query |
**Example:**
```python
-from semantica.vector_store import HybridSearch
+from semantica.vector_store import HybridSearch, MetadataFilter
-hybrid = HybridSearch(
- vector_store=store,
- keyword_index=keyword_index,
- fusion_method="rrf", # rrf, weighted, cascade
- vector_weight=0.7 # for weighted fusion
-)
+searcher = HybridSearch(store)
+filters = MetadataFilter().eq("category", "news").gt("date", "2023-01-01")
-results = hybrid.search(
- query="machine learning applications",
- top_k=10
+results = searcher.search(
+ query_vector=emb,
+ filter=filters,
+ k=10
)
```
----
-
-### VectorRetriever
-
-
-**Methods:**
+### Adapters
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `retrieve(query, top_k)` | Retrieve relevant documents | Vector search + document fetching |
-| `retrieve_batch(queries, top_k)` | Batch retrieval | Parallel vector search |
-| `retrieve_with_context(query, context_size)` | Retrieve with context | Sliding window context expansion |
-| `filter_by_metadata(results, filters)` | Filter by metadata | Post-search filtering |
+Backend-specific implementations:
+- `FAISSAdapter`: Local, in-memory/disk.
+- `PineconeAdapter`: Managed cloud service.
+- `WeaviateAdapter`: Schema-aware vector DB.
+- `QdrantAdapter`: Rust-based high-performance DB.
+- `MilvusAdapter`: Scalable cloud-native DB.
---
-## Index Types Comparison
-
-### FAISS Index Types
+## Convenience Functions
-| Index Type | Build Time | Search Time | Memory | Recall | Use Case |
-|------------|------------|-------------|--------|--------|----------|
-| **Flat** | O(1) | O(n*d) | High | 1.00 | Small datasets, exact search |
-| **IVF** | O(n*d) | O(√n*d) | Medium | 0.95 | Medium datasets, good balance |
-| **HNSW** | O(n*log n*d) | O(log n*d) | High | 0.98 | Large datasets, fast search |
-| **PQ** | O(n*d) | O(n) | Low | 0.85 | Memory-constrained, compression |
+```python
+from semantica.vector_store import store_vectors, search_vectors
-### Index Parameters
+# Quick usage (uses default configured backend)
+store_vectors(embeddings, metadata)
+results = search_vectors(query_embedding)
+```
-**IVF Parameters:**
-- `nlist`: Number of clusters (√n to 4√n recommended)
-- `nprobe`: Number of clusters to search (1-nlist)
+---
-**HNSW Parameters:**
-- `M`: Number of connections per layer (4-64, default: 16)
-- `efConstruction`: Construction time accuracy (100-500)
-- `efSearch`: Search time accuracy (efConstruction to 2*efConstruction)
+## Configuration
-**PQ Parameters:**
-- `m`: Number of subquantizers (dimension/m should be divisible)
-- `nbits`: Bits per subquantizer (8 is standard)
+### Environment Variables
----
+```bash
+export VECTOR_STORE_BACKEND=pinecone
+export PINECONE_API_KEY=sk-...
+export PINECONE_ENV=us-west1-gcp
+```
-## Configuration
+### YAML Configuration
```yaml
-# config.yaml - Vector Store Configuration
-
vector_store:
- backend: faiss # faiss, pinecone, qdrant, weaviate, milvus
+ backend: faiss # or pinecone, weaviate, etc.
+ dimension: 1536
+ metric: cosine
faiss:
- index_type: HNSW # Flat, IVF, HNSW, PQ
- metric: cosine # cosine, euclidean, dot_product
- dimension: 1536
+ index_type: HNSW
- # HNSW parameters
- hnsw_m: 16
- hnsw_ef_construction: 200
- hnsw_ef_search: 100
-
- # IVF parameters
- ivf_nlist: 100
- ivf_nprobe: 10
-
- hybrid_search:
- fusion_method: rrf # rrf, weighted, cascade
- vector_weight: 0.7
- keyword_weight: 0.3
- enable_reranking: true
-
- batch_operations:
- batch_size: 1000
- parallel_workers: 4
+ pinecone:
+ environment: us-west1-gcp
+ index_name: my-index
+```
+
+---
+
+## Integration Examples
+
+### RAG Retrieval
+
+```python
+from semantica.embeddings import EmbeddingGenerator
+from semantica.vector_store import VectorStore
+
+# 1. Embed Query
+embedder = EmbeddingGenerator()
+query_vec = embedder.generate("What is the capital of France?")
+
+# 2. Search
+store = VectorStore()
+results = store.search(query_vec, k=3)
+
+# 3. Use Context
+context = "\n".join([r.metadata['text'] for r in results])
+print(f"Context: {context}")
```
---
-## Performance Characteristics
+## Best Practices
-### Search Complexity
+1. **Normalize Vectors**: Always normalize vectors if using Cosine Similarity or Dot Product.
+2. **Use HNSW**: For FAISS, `HNSW` is usually the best default index type for performance/recall balance.
+3. **Batch Operations**: Use `store_vectors` with batches (e.g., 100 items) rather than one by one.
+4. **Filter First**: In hybrid search, restrictive filters significantly improve performance.
-| Index Type | Build | Search | Memory |
-|------------|-------|--------|--------|
-| Flat | O(1) | O(n*d) | O(n*d) |
-| IVF | O(n*d*k) | O(√n*d) | O(n*d) |
-| HNSW | O(n*log n*d) | O(log n*d) | O(n*d*M) |
-| PQ | O(n*d) | O(n*m) | O(n*m) |
+---
-where n = vectors, d = dimensions, k = clusters, M = HNSW connections, m = subquantizers
+## Troubleshooting
-### Scalability
+**Issue**: `DimensionMismatchError`
+**Solution**: Ensure your embedding model dimension (e.g., 1536 for OpenAI) matches the VectorStore dimension.
-- **Small (<10K vectors)**: Use Flat for exact search
-- **Medium (10K-1M vectors)**: Use IVF or HNSW
-- **Large (>1M vectors)**: Use HNSW with GPU or distributed systems
-- **Very Large (>10M vectors)**: Use distributed backends (Milvus, Weaviate)
+**Issue**: FAISS index not saved.
+**Solution**: Call `store.save("index.faiss")` explicitly for local FAISS indices, or use a persistent backend like Pinecone/Qdrant.
---
## See Also
-- [Embeddings Module](embeddings.md) - Generate vector embeddings
-- [Knowledge Graph Module](kg.md) - Graph-based retrieval
-- [Core Module](core.md) - Framework orchestration
+- [Embeddings Module](embeddings.md) - Generates the vectors
+- [Context Module](context.md) - Uses vector store for memory
+- [Ingest Module](ingest.md) - Source of data
diff --git a/docs/reference/visualization.md b/docs/reference/visualization.md
index 6bb1f8c9..c04d58b9 100644
--- a/docs/reference/visualization.md
+++ b/docs/reference/visualization.md
@@ -1,29 +1,76 @@
-# Visualization Module
+# Visualization
-Visualize knowledge graphs, embeddings, and analytics with interactive and static visualizations using multiple rendering engines.
+> **Comprehensive visualization suite for Knowledge Graphs, Ontologies, Embeddings, and Temporal data.**
-## Overview
+---
+
+## 🎯 Overview
+
+<div class="grid cards" markdown>
+
+- :material-graph:{ .lg .middle } **KG Visualization**
+
+ ---
+
+ Interactive network graphs with Force-directed, Hierarchical, and Circular layouts
+
+- :material-file-tree:{ .lg .middle } **Ontology View**
+
+ ---
+
+ Visualize class hierarchies, property domains/ranges, and taxonomy trees
+
+- :material-chart-scatter-plot:{ .lg .middle } **Embedding Projector**
+
+ ---
+
+ 2D/3D visualization of vector embeddings using UMAP, t-SNE, and PCA
+
+- :material-clock-time-four-outline:{ .lg .middle } **Temporal Analysis**
+
+ ---
+
+ Timeline views and graph evolution visualization
+
+- :material-chart-bar:{ .lg .middle } **Analytics Dashboards**
+
+ ---
-- **Graph Visualization**: Interactive and static knowledge graph rendering
-- **Embedding Visualization**: t-SNE, UMAP, PCA for high-dimensional data
-- **Analytics Visualization**: Charts, plots, and dashboards
-- **Temporal Visualization**: Time-series and evolution visualization
-- **Export Formats**: HTML, PNG, SVG, PDF
+ Visual dashboards for centrality, community structure, and connectivity
+
+- :material-export:{ .lg .middle } **Multi-Format Export**
+
+ ---
+
+ Export to HTML (interactive), PNG, SVG, PDF, and JSON
+
+</div>
+
+!!! tip "When to Use"
+ - **Exploration**: Interactively explore graph connections and clusters
+ - **Reporting**: Generate static charts for reports and presentations
+ - **Debugging**: Visually inspect graph structure and disconnected components
+ - **Analysis**: Identify patterns, outliers, and trends in data
---
-## Algorithms Used
+## ⚙️ Algorithms Used
+
+### Layout Algorithms
+- **Force-Directed**: Simulates physical forces (repulsion between nodes, springs for edges) to find equilibrium.
+- **Hierarchical**: Tree-based layout for taxonomies and directed acyclic graphs (DAGs).
+- **Circular**: Arranges nodes in a circle, useful for analyzing interconnectivity.
+- **Community-Based**: Groups nodes by community (Louvain/Leiden) and separates clusters.
### Dimensionality Reduction
-- **t-SNE (t-Distributed Stochastic Neighbor Embedding)**: Non-linear dimensionality reduction, preserves local structure
-- **UMAP (Uniform Manifold Approximation and Projection)**: Faster than t-SNE, preserves global + local structure
-- **PCA (Principal Component Analysis)**: Linear dimensionality reduction, `X_reduced = X * eigenvectors`
+- **UMAP**: Uniform Manifold Approximation and Projection. Preserves global structure better than t-SNE.
+- **t-SNE**: t-Distributed Stochastic Neighbor Embedding. Good for local clustering.
+- **PCA**: Principal Component Analysis. Linear projection for variance maximization.
-### Graph Layout Algorithms
-- **Force-Directed Layout**: Spring-electrical model with Fruchterman-Reingold algorithm
-- **Hierarchical Layout**: Tree-based layout with Sugiyama framework
-- **Circular Layout**: Nodes arranged in circle, edges minimize crossings
-- **Kamada-Kawai**: Energy-based layout minimizing edge length variance
+### Analytics Visualization
+- **Centrality Sizing**: Node size proportional to Degree/Betweenness/PageRank.
+- **Heatmaps**: Matrix visualization for adjacency or similarity.
+- **Sankey Diagrams**: Flow visualization for lineage or process steps.
---
@@ -31,151 +78,154 @@ Visualize knowledge graphs, embeddings, and analytics with interactive and stati
### KGVisualizer
+Visualizes Knowledge Graph structure and communities.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `visualize(graph, output)` | Visualize knowledge graph | Force-directed layout with PyVis/Cytoscape |
-| `render_interactive(graph)` | Interactive HTML visualization | D3.js/PyVis rendering |
-| `render_static(graph, format)` | Static image rendering | Graphviz/Matplotlib rendering |
-| `export(graph, filename, format)` | Export visualization | Format-specific export (HTML/PNG/SVG) |
-| `customize_style(node_style, edge_style)` | Customize appearance | Style application |
-
-**Supported Engines:**
-- **PyVis**: Interactive HTML with physics simulation
-- **Cytoscape.js**: Web-based graph visualization
-- **Graphviz**: Static high-quality diagrams
-- **Matplotlib**: Python-native plotting
-- **Plotly**: Interactive web visualizations
+| Method | Description |
+|--------|-------------|
+| `visualize_network(graph)` | Standard network plot |
+| `visualize_communities(graph)` | Color by community |
+| `visualize_path(path)` | Highlight specific path |
**Example:**
```python
from semantica.visualization import KGVisualizer
-visualizer = KGVisualizer(
- engine="pyvis", # pyvis, cytoscape, graphviz, matplotlib
- layout="force_directed", # force_directed, hierarchical, circular
- width="100%",
- height="800px"
-)
+viz = KGVisualizer(layout="force", height=800)
+fig = viz.visualize_network(kg, output="interactive")
+fig.write_html("graph.html")
+```
-# Interactive visualization
-visualizer.visualize(
- graph=kg,
- output="graph.html",
- show_physics=True,
- node_color_by="type",
- edge_width_by="weight"
-)
+### OntologyVisualizer
-# Static visualization
-visualizer.render_static(
- graph=kg,
- format="png",
- output="graph.png",
- dpi=300
-)
-```
+Visualizes schema and taxonomy.
----
+**Methods:**
+
+| Method | Description |
+|--------|-------------|
+| `visualize_hierarchy(ontology)` | Tree view of classes |
+| `visualize_properties(ontology)` | Property domain/range graph |
### EmbeddingVisualizer
+Project high-dimensional vectors to 2D/3D.
**Methods:**
| Method | Description | Algorithm |
|--------|-------------|-----------|
-| `visualize(embeddings, method)` | Visualize embeddings | Dimensionality reduction + scatter plot |
-| `plot_tsne(embeddings, perplexity)` | t-SNE visualization | t-SNE with configurable perplexity |
-| `plot_umap(embeddings, n_neighbors)` | UMAP visualization | UMAP with neighbor parameter |
-| `plot_pca(embeddings, n_components)` | PCA visualization | PCA to 2D/3D |
-| `plot_clusters(embeddings, labels)` | Cluster visualization | Color-coded scatter plot |
-
-**t-SNE Parameters:**
-- `perplexity`: Balance between local and global structure (5-50)
-- `learning_rate`: Step size (10-1000)
-- `n_iter`: Number of iterations (250-1000)
-
-**UMAP Parameters:**
-- `n_neighbors`: Local neighborhood size (2-100)
-- `min_dist`: Minimum distance between points (0.0-0.99)
-- `metric`: Distance metric (euclidean, cosine, manhattan)
+| `visualize_2d(embeddings)` | 2D Scatter plot | UMAP/t-SNE |
+| `visualize_3d(embeddings)` | 3D Scatter plot | UMAP/t-SNE |
+| `visualize_clusters(embeddings)` | Colored by cluster | K-Means/DBSCAN |
**Example:**
```python
from semantica.visualization import EmbeddingVisualizer
-visualizer = EmbeddingVisualizer()
-
-# t-SNE visualization
-visualizer.plot_tsne(
- embeddings=embeddings,
- labels=labels,
- perplexity=30,
- output="tsne.html"
-)
-
-# UMAP visualization
-visualizer.plot_umap(
- embeddings=embeddings,
- n_neighbors=15,
- min_dist=0.1,
- output="umap.html"
+viz = EmbeddingVisualizer()
+viz.visualize_2d_projection(
+ embeddings,
+ labels=labels,
+ method="umap",
+ output="embeddings.html"
)
```
----
-
-### AnalyticsVisualizer
+### TemporalVisualizer
+Visualizes time-series and graph evolution.
**Methods:**
-| Method | Description | Algorithm |
-|--------|-------------|-----------|
-| `plot_metrics(metrics)` | Plot graph metrics | Bar/line charts |
-| `plot_distribution(data, bins)` | Plot distributions | Histogram generation |
-| `plot_timeline(events, timeline)` | Plot temporal data | Time-series visualization |
-| `create_dashboard(components)` | Create dashboard | Multi-panel layout |
+| Method | Description |
+|--------|-------------|
+| `visualize_timeline(events)` | Event timeline |
+| `visualize_evolution(snapshots)` | Graph changes over time |
+
+---
+
+## Convenience Functions
+
+```python
+from semantica.visualization import visualize_kg, visualize_embeddings
+
+# One-line visualization
+visualize_kg(kg, output="graph.html")
+visualize_embeddings(embeddings, method="umap")
+```
---
## Configuration
-```yaml
-# config.yaml - Visualization Configuration
+### Environment Variables
+
+```bash
+export VIZ_DEFAULT_LAYOUT=force
+export VIZ_COLOR_SCHEME=vibrant
+export VIZ_RENDERER=plotly
+```
+### YAML Configuration
+
+```yaml
visualization:
- kg:
- engine: pyvis # pyvis, cytoscape, graphviz, matplotlib
- layout: force_directed
- width: "100%"
- height: "800px"
- physics_enabled: true
- node_size_by: degree
- node_color_by: type
- edge_width_by: weight
+ layout:
+ algorithm: force
+ iterations: 50
- embeddings:
- method: umap # tsne, umap, pca
- n_components: 2
- perplexity: 30 # for t-SNE
- n_neighbors: 15 # for UMAP
+ style:
+ node_size: 10
+ edge_width: 1
+ color_scheme: "vibrant" # vibrant, pastel, dark
export:
- format: html # html, png, svg, pdf
- dpi: 300 # for raster formats
- transparent_background: false
+ width: 1200
+ height: 800
+ scale: 2.0
+```
+
+---
+
+## Integration Examples
+
+### Exploratory Data Analysis (EDA)
+
+```python
+from semantica.ingest import Ingestor
+from semantica.kg import KnowledgeGraph
+from semantica.visualization import KGVisualizer, AnalyticsVisualizer
+
+# 1. Load Data
+kg = KnowledgeGraph.load("my_graph")
+
+# 2. Visualize Structure
+kg_viz = KGVisualizer()
+kg_viz.visualize_network(kg, output="structure.html")
+
+# 3. Visualize Analytics
+analytics_viz = AnalyticsVisualizer()
+analytics_viz.visualize_centrality(kg, output="centrality.png")
+analytics_viz.visualize_degree_distribution(kg, output="degree_dist.png")
```
---
+## Best Practices
+
+1. **Filter First**: Don't try to visualize 1M nodes. Filter to a subgraph of <5000 nodes for readability.
+2. **Use Interactive**: Interactive HTML plots (Plotly) allow zooming and hovering, which is essential for dense graphs.
+3. **Color Meaningfully**: Use color to represent node types or communities, not just random assignment.
+4. **Size by Importance**: Map node size to centrality (e.g., PageRank) to highlight important entities.
+
+---
+
## See Also
-- [Knowledge Graph Module](kg.md)
-- [Embeddings Module](embeddings.md)
-- [Export Module](export.md)
+- [Knowledge Graph Module](kg.md) - The data source
+- [Embeddings Module](embeddings.md) - Source for vector visualizations
+- [Ontology Module](ontology.md) - Source for hierarchy visualizations
diff --git a/mkdocs.yml b/mkdocs.yml
index e5b7ddeb..828eda0a 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -104,19 +104,25 @@ nav:
- installation.md
- quickstart.md
- Docs:
+ - Conflicts: reference/conflicts.md
+ - Context: reference/context.md
- Core: reference/core.md
+ - Deduplication: reference/deduplication.md
- Embeddings: reference/embeddings.md
- Evals: reference/evals.md
- Export: reference/export.md
- Graph Store: reference/graph_store.md
- Ingest: reference/ingest.md
+ - KG QA: reference/kg_qa.md
- Knowledge Graph: reference/kg.md
- Normalize: reference/normalize.md
- Ontology: reference/ontology.md
- Parse: reference/parse.md
- Pipeline: reference/pipeline.md
- Reasoning: reference/reasoning.md
+ - Seed: reference/seed.md
- Semantic Extract: reference/semantic_extract.md
+ - Split: reference/split.md
- Triple Store: reference/triple_store.md
- Utils: reference/utils.md
- Vector Store: reference/vector_store.md