Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Refactor documentation: Improve structure, formatting, and remove unused charts in Guide Tab

KaifAhmad1bb04a818b01f
diff --git a/docs/concepts.md b/docs/concepts.md
index 1a4cc156..6b686450 100644
--- a/docs/concepts.md
+++ b/docs/concepts.md
@@ -7,117 +7,7 @@ Understand the fundamental concepts behind Semantica. This guide covers the theo
---
-## Table of Contents
-
-- [Prerequisites](#prerequisites)
-- [Learning Objectives](#learning-objectives)
-- [Concept Map](#concept-map)
-- [Core Concepts](#core-concepts)
- - [Knowledge Graphs](#1-knowledge-graphs)
- - [Entity Extraction (NER)](#2-entity-extraction-ner)
- - [Relationship Extraction](#3-relationship-extraction)
- - [Embeddings](#4-embeddings)
- - [Temporal Graphs](#5-temporal-graphs)
- - [GraphRAG](#6-graphrag)
- - [Ontology](#7-ontology)
- - [Quality Assurance](#8-quality-assurance)
- - [Deduplication & Entity Resolution](#9-deduplication--entity-resolution)
- - [Data Normalization](#10-data-normalization)
- - [Conflict Detection](#11-conflict-detection)
-- [Comparison Tables](#comparison-tables)
-- [Best Practices](#best-practices)
-- [Troubleshooting](#troubleshooting)
----
-
-## Prerequisites
-
-Before diving into the core concepts, you should have:
-
-- Basic understanding of Python programming
-- Familiarity with data structures (lists, dictionaries, graphs)
-- General knowledge of machine learning concepts (helpful but not required)
-- Understanding of text processing basics
-
-!!! tip "New to Knowledge Graphs?"
- If you're completely new to knowledge graphs, start with the [Getting Started Guide](getting-started.md) and [Quickstart Tutorial](quickstart.md) before reading this guide.
-
----
-
-## Learning Objectives
-
-By the end of this guide, you will understand:
-
-- What knowledge graphs are and how they represent information
-- How entity and relationship extraction works
-- The role of embeddings in semantic understanding
-- How temporal graphs track changes over time
-- How GraphRAG enhances LLM applications
-- The importance of ontologies and quality assurance
-- How to resolve conflicts and deduplicate entities
-- When to use each concept in your applications
-
----
-
-## Concept Map
-
-The following diagram shows how the core concepts in Semantica relate to each other:
-
-```mermaid
-graph TB
- subgraph Data["Data Sources"]
- Raw[Raw Data]
- end
-
- subgraph Processing["Processing Pipeline"]
- Ingest[Ingestion]
- Parse[Parsing]
- Norm[Normalization]
- Extract[Entity/Relation Extraction]
- end
-
- subgraph Core["Core Concepts"]
- KG[Knowledge Graph]
- Embed[Embeddings]
- Temp[Temporal Graphs]
- Onto[Ontology]
- end
-
- subgraph Quality["Quality Assurance"]
- Dedup[Deduplication]
- Conflict[Conflict Detection]
- QA[Quality Metrics]
- end
-
- subgraph Application["Applications"]
- GraphRAG[GraphRAG]
- Search[Semantic Search]
- Reason[Reasoning]
- end
-
- Raw --> Ingest
- Ingest --> Parse
- Parse --> Norm
- Norm --> Extract
- Extract --> KG
- Extract --> Embed
- KG --> Temp
- KG --> Onto
- KG --> Dedup
- KG --> Conflict
- Dedup --> QA
- Conflict --> QA
- KG --> GraphRAG
- Embed --> Search
- KG --> Reason
- Onto --> QA
-
- style KG fill:#e3f2fd,stroke:#1565c0,stroke-width:3px
- style Embed fill:#fff3e0,stroke:#ef6c00,stroke-width:2px
- style GraphRAG fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
-```
-
----
## Core Concepts
@@ -126,23 +16,29 @@ graph TB
!!! abstract "Definition"
A **knowledge graph** is a structured representation of entities (nodes) and their relationships (edges) with properties and attributes. It transforms unstructured data into a queryable, interconnected knowledge base.
-**Key Components**:
+<div class="grid cards" markdown>
-- **Nodes (Entities)**: Represent real-world objects, concepts, or events
- - Examples: People, Organizations, Locations, Concepts
-- **Edges (Relationships)**: Represent connections between entities
- - Examples: `works_for`, `located_in`, `founded_by`, `causes`
-- **Properties**: Attributes of entities and relationships
- - Examples: Name, Date, Confidence Score, Source
-- **Metadata**: Additional information about the data
- - Examples: Source documents, timestamps, extraction methods
-
-??? info "Deep Dive: Graph Theory Basics"
- At its core, a knowledge graph is a directed multigraph $G = (V, E)$ where:
- - $V$ is a set of vertices (entities)
- - $E$ is a set of edges (relationships)
- - Edges are directed: $(u, v) \in E$ implies a relationship from $u$ to $v$
- - Multigraph property allows multiple edges between the same pair of vertices (e.g., "Friend" and "Colleague")
+- **Nodes (Entities)**
+ ---
+ Represent real-world objects, concepts, or events.
+ *Examples*: People, Organizations, Locations, Concepts
+
+- **Edges (Relationships)**
+ ---
+ Represent connections between entities.
+ *Examples*: `works_for`, `located_in`, `founded_by`, `causes`
+
+- **Properties**
+ ---
+ Attributes of entities and relationships.
+ *Examples*: Name, Date, Confidence Score, Source
+
+- **Metadata**
+ ---
+ Additional information about the data.
+ *Examples*: Source documents, timestamps, extraction methods
+
+</div>
**Visual Example**:
@@ -186,14 +82,6 @@ for entity in kg['entities'][:5]:
print(f"- {entity.get('text', 'N/A')}: {entity.get('type', 'N/A')}")
```
-**When to Use**:
-
-- You need to model complex relationships between entities
-- You want to query data using graph patterns
-- You need to track how information changes over time
-- You're building a semantic search or RAG application
-- You need to integrate data from multiple sources
-
**Related Modules**:
- [`kg` Module](reference/kg.md) - Knowledge graph construction and management
@@ -263,35 +151,6 @@ for entity in kg['entities'][:5]:
entities = ner.extract_entities(text)
```
-**Practical Example**:
-
-```python
-from semantica.semantic_extract import NamedEntityRecognizer
-
-# Initialize NER
-ner = NamedEntityRecognizer()
-
-# Extract entities from text
-text = """
-Apple Inc. was founded by Steve Jobs in Cupertino, California in 1976.
-The company designs and manufactures consumer electronics and software.
-Tim Cook is the current CEO of Apple.
-"""
-
-entities = ner.extract_entities(text)
-
-print("Extracted Entities:")
-for entity in entities:
- print(f" - {entity.text} ({entity.label}) - Confidence: {entity.confidence:.2f}")
-```
-
-**When to Use**:
-
-- You need to identify key entities in unstructured text
-- You're building a knowledge graph from documents
-- You want to extract structured information from text
-- You need to categorize mentions in your data
-
**Related Modules**:
- [`semantic_extract` Module](reference/semantic_extract.md) - Entity and relationship extraction
- [`ontology` Module](reference/ontology.md) - Custom entity type definitions
@@ -363,32 +222,6 @@ graph LR
style F fill:#e3f2fd
```
-**Practical Example**:
-
-```python
-from semantica.semantic_extract import NamedEntityRecognizer, RelationExtractor
-
-# Extract entities first
-ner = NamedEntityRecognizer()
-entities = ner.extract_entities(text)
-
-# Extract relationships
-rel_extractor = RelationExtractor()
-relationships = rel_extractor.extract_relations(text, entities=entities)
-
-print("Extracted Relationships:")
-for rel in relationships:
- print(f" {rel.subject.text} --[{rel.predicate}]--> {rel.object.text}")
- print(f" Confidence: {rel.confidence:.2f}, Source: {rel.source}")
-```
-
-**When to Use**:
-
-- You need to connect entities in your knowledge graph
-- You want to understand how entities relate to each other
-- You're building a semantic network
-- You need to model complex relationships
-
**Related Modules**:
- [`semantic_extract` Module](reference/semantic_extract.md) - Relationship extraction
- [`kg` Module](reference/kg.md) - Building graphs from relationships
@@ -428,39 +261,6 @@ Embedding: [0.123, -0.456, 0.789, ..., 0.234] # (vector of 1536 dimensions)
| **HuggingFace** | sentence-transformers | 384-768 | Medium | Free | Development, open source |
| **Local** | Various | Variable | Slow | Free | Privacy, offline use |
-**Practical Example**:
-
-```python
-from semantica.embeddings import EmbeddingGenerator
-
-# Initialize embedding generator
-generator = EmbeddingGenerator(
- provider="openai",
- model="text-embedding-3-small"
-)
-
-# Generate embeddings
-texts = [
- "Machine learning is a subset of artificial intelligence",
- "Deep learning uses neural networks",
- "Python is a programming language"
-]
-
-embeddings = generator.generate(texts)
-
-# Find similar texts
-similarity = generator.similarity(embeddings[0], embeddings[1])
-print(f"Similarity: {similarity:.2f}") # High similarity
-```
-
-**When to Use**:
-
-- You need semantic search capabilities
-- You want to find similar documents or concepts
-- You're building a RAG application
-- You need to cluster or classify text
-- You want to measure semantic similarity
-
**Related Modules**:
- [`embeddings` Module](reference/embeddings.md) - Embedding generation
- [`vector_store` Module](reference/vector_store.md) - Vector storage and search
@@ -494,45 +294,6 @@ timeline
: Relationship A->B expired
```
-**Practical Example**:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica(temporal=True)
-
-# Build temporal knowledge graph
-result = semantica.build_knowledge_base(
- sources=["historical_data.pdf"],
- temporal=True
-)
-
-kg = result["knowledge_graph"]
-
-# Query graph at specific time
-historical_state = semantica.kg.query_at_time(
- kg,
- timestamp="2022-01-01",
- query="MATCH (e:Entity) RETURN e"
-)
-
-# Track entity changes
-changes = semantica.kg.get_entity_history(
- kg,
- entity_id="entity_123",
- start_time="2020-01-01",
- end_time="2023-12-31"
-)
-```
-
-**When to Use**:
-
-- You need to track how information changes over time
-- You're analyzing historical data
-- You need to query past states of your knowledge
-- You're building time-aware applications
-- You need to detect trends and patterns over time
-
**Related Modules**:
- [`kg` Module](reference/kg.md) - Temporal graph support
- [`visualization` Module](reference/visualization.md) - Temporal visualization
@@ -583,39 +344,6 @@ flowchart TD
| **Complex Queries** | Limited | Excellent |
| **Relationship Awareness** | No | Yes |
-**Practical Example**:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-
-# Build knowledge base with graph
-result = semantica.build_knowledge_base(
- sources=["documents/"],
- embeddings=True,
- graph=True
-)
-
-# Use GraphRAG for querying
-answer = semantica.graphrag.query(
- query="What is the relationship between Company A and Company B?",
- knowledge_graph=result["knowledge_graph"],
- embeddings=result["embeddings"],
- top_k=5
-)
-
-print(answer)
-```
-
-**When to Use**:
-
-- You're building a RAG application
-- You need accurate, context-aware answers
-- You want to reduce LLM hallucinations
-- You need to answer complex, multi-hop questions
-- You need relationship-aware retrieval
-
**Related Modules**:
- [`kg` Module](reference/kg.md) - Knowledge graph construction
- [`vector_store` Module](reference/vector_store.md) - Vector search
@@ -658,34 +386,6 @@ classDiagram
Company --> Location : locatedIn
```
-**Practical Example**:
-
-```python
-from semantica.ontology import OntologyGenerator
-
-# Generate ontology from knowledge graph
-generator = OntologyGenerator()
-
-ontology = generator.generate_from_graph(
- knowledge_graph=kg,
- base_uri="https://example.org/ontology/"
-)
-
-# Validate ontology
-validator = generator.validate(ontology)
-
-# Export to OWL
-generator.export_owl(ontology, "output.owl")
-```
-
-**When to Use**:
-
-- You need to define a consistent schema for your domain
-- You want to ensure data consistency
-- You're integrating with other systems
-- You need to enforce constraints and rules
-- You want to enable reasoning
-
**Related Modules**:
- [`ontology` Module](reference/ontology.md) - Ontology generation and management
- [`kg` Module](reference/kg.md) - Knowledge graph construction
@@ -707,33 +407,6 @@ generator.export_owl(ontology, "output.owl")
| **Coverage** | Breadth of domain coverage | Entity diversity, relationship types |
| **Freshness** | How up-to-date the data is | Last update timestamp, staleness |
-**Quality Metrics Example**:
-
-```python
-from semantica.kg_qa import KGQualityAssessor
-
-# Assess knowledge graph quality
-assessor = KGQualityAssessor()
-metrics = assessor.assess(kg)
-
-print(f"Completeness: {metrics.completeness:.2%}")
-print(f"Consistency: {metrics.consistency:.2%}")
-print(f"Accuracy: {metrics.accuracy:.2%}")
-print(f"Coverage: {metrics.coverage:.2%}")
-
-# Get quality report
-report = assessor.generate_report(kg)
-print(report)
-```
-
-**When to Use**:
-
-- You need to validate your knowledge graph
-- You want to ensure data quality
-- You're preparing data for production
-- You need to identify data issues
-- You want to measure improvement over time
-
**Related Modules**:
- [`kg_qa` Module](reference/evals.md) - Quality assurance and evaluation
- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection
@@ -755,36 +428,6 @@ print(report)
Deduplication works by calculating similarity between entities. If similarity exceeds a threshold, entities are merged; otherwise, they remain separate.
-**Practical Example**:
-
-```python
-from semantica.deduplication import Deduplicator
-
-# Initialize deduplicator
-deduplicator = Deduplicator(
- similarity_threshold=0.85,
- method="embedding"
-)
-
-# Detect duplicates
-duplicates = deduplicator.detect_duplicates(kg)
-
-# Merge duplicates
-merged_kg = deduplicator.merge(kg, duplicates)
-
-print(f"Original entities: {len(kg['entities'])}")
-print(f"Merged entities: {len(merged_kg['entities'])}")
-print(f"Duplicates found: {len(duplicates)}")
-```
-
-**When to Use**:
-
-- You're integrating data from multiple sources
-- You have variations in entity names
-- You want to reduce graph redundancy
-- You need to improve query accuracy
-- You're cleaning your knowledge graph
-
**Related Modules**:
- [`deduplication` Module](../semantica/deduplication/deduplication_usage.md) - Deduplication and merging
- [`embeddings` Module](reference/embeddings.md) - Similarity calculation
@@ -796,14 +439,6 @@ print(f"Duplicates found: {len(duplicates)}")
!!! abstract "Definition"
**Data Normalization** is the process of cleaning and standardizing data into a consistent format, ensuring uniformity across your knowledge graph.
-**Normalization Steps**:
-
-1. **Text Cleaning**: Remove noise, fix encoding issues
-2. **Entity Normalization**: Standardize entity names and formats
-3. **Date Normalization**: Convert dates to ISO format
-4. **Number Normalization**: Standardize numeric formats
-5. **Language Detection**: Identify and handle multiple languages
-
**Normalization Pipeline**:
```mermaid
@@ -818,36 +453,6 @@ flowchart LR
style Normalized fill:#c8e6c9
```
-**Practical Example**:
-
-```python
-from semantica.normalize import TextNormalizer
-
-# Initialize normalizer
-normalizer = TextNormalizer()
-
-# Normalize text
-raw_text = "Apple Inc. was founded on April 1, 1976 in Cupertino, CA."
-normalized = normalizer.normalize(raw_text)
-
-# Normalize entities
-entities = [
- {"text": "Apple Inc.", "type": "ORG"},
- {"text": "apple inc", "type": "ORG"}, # Duplicate with different case
-]
-
-normalized_entities = normalizer.normalize_entities(entities)
-# Result: Both normalized to "Apple Inc."
-```
-
-**When to Use**:
-
-- You have inconsistent data formats
-- You're processing data from multiple sources
-- You need to standardize entity names
-- You want to improve extraction accuracy
-- You're preparing data for deduplication
-
**Related Modules**:
- [`normalize` Module](reference/normalize.md) - Data normalization
- [`parse` Module](reference/parse.md) - Document parsing
@@ -905,36 +510,6 @@ normalized_entities = normalizer.normalize_entities(entities)
resolved = resolver.resolve(conflicts)
```
-**Practical Example**:
-
-```python
-from semantica.conflicts import ConflictDetector, ConflictResolver
-
-# Detect conflicts
-detector = ConflictDetector()
-conflicts = detector.detect(kg)
-
-print(f"Found {len(conflicts)} conflicts")
-
-# Resolve conflicts
-resolver = ConflictResolver(strategy="voting")
-resolved_kg = resolver.resolve_conflicts(kg, conflicts)
-
-# Investigate specific conflicts
-for conflict in conflicts[:5]:
- print(f"Conflict: {conflict.entity}")
- print(f" Sources: {conflict.sources}")
- print(f" Values: {conflict.values}")
-```
-
-**When to Use**:
-
-- You're integrating data from multiple sources
-- You have conflicting information
-- You need to ensure data consistency
-- You want to track data provenance
-- You're building a reliable knowledge base
-
**Related Modules**:
- [`conflicts` Module](../semantica/conflicts/conflicts_usage.md) - Conflict detection and resolution
- [`kg_qa` Module](reference/evals.md) - Quality assurance
@@ -947,24 +522,20 @@ for conflict in conflicts[:5]:
| Provider | Model | Dimensions | Speed | Cost | Accuracy | Best For |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
-| Provider | Model | Dimensions | Speed | Cost | Accuracy | Best For |
-| :------------ | :--------------------- | :--------- | :------ | :---- | :------- | :-------------------------- |
-| **OpenAI** | text-embedding-3-large | 3072 | Fast | Paid | High | Production, high accuracy |
-| **OpenAI** | text-embedding-3-small | 1536 | Fast | Paid | High | Balanced performance |
-| **Cohere** | embed-english-v3.0 | 1024 | Fast | Paid | High | Multilingual support |
-| **HuggingFace**| all-MiniLM-L6-v2 | 384 | Medium | Free | Medium | Development, open source |
-| **Local** | sentence-transformers | 384-768 | Slow | Free | Medium | Privacy, offline use |
+| **OpenAI** | text-embedding-3-large | 3072 | Fast | Paid | High | Production, high accuracy |
+| **OpenAI** | text-embedding-3-small | 1536 | Fast | Paid | High | Balanced performance |
+| **Cohere** | embed-english-v3.0 | 1024 | Fast | Paid | High | Multilingual support |
+| **HuggingFace** | all-MiniLM-L6-v2 | 384 | Medium | Free | Medium | Development, open source |
+| **Local** | sentence-transformers | 384-768 | Slow | Free | Medium | Privacy, offline use |
### Graph Backend Comparison
| Backend | Type | Speed | Scalability | Query Language | Best For |
| :--- | :--- | :--- | :--- | :--- | :--- |
-| Backend | Type | Speed | Scalability | Query Language | Best For |
-| :--------- | :---------- | :-------- | :---------- | :------------- | :-------------------------------- |
-| **NetworkX**| In-memory | Fast | Small-medium| Python API | Development, small graphs |
-| **Neo4j** | Database | Medium | Large | Cypher | Production, complex queries |
-| **KuzuDB** | Embedded | Fast | Medium | Cypher | Embedded applications |
-| **FalkorDB**| Redis-based| Very Fast | Large | Cypher | Real-time, high throughput |
+| **NetworkX**| In-memory | Fast | Small-medium | Python API | Development, small graphs |
+| **Neo4j** | Database | Medium | Large | Cypher | Production, complex queries |
+| **KuzuDB** | Embedded | Fast | Medium | Cypher | Embedded applications |
+| **FalkorDB**| Redis-based| Very Fast | Large | Cypher | Real-time, high throughput |
---
diff --git a/docs/examples.md b/docs/examples.md
index 4fcada8e..1b9ab908 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -7,34 +7,46 @@ Real-world examples and use cases for Semantica.
---
-## Table of Contents
+## Example Gallery
-- [Getting Started (5 min examples)](#getting-started-5-min-examples)
-- [Core Workflows (15 min examples)](#core-workflows-15-min-examples)
-- [Advanced Patterns (30+ min examples)](#advanced-patterns-30-min-examples)
-- [Production Patterns](#production-patterns)
+<div class="grid cards" markdown>
----
+- :material-school: **Getting Started**
+ ---
+ Quick examples to get you up and running in 5 minutes.
+
+ [View Examples](#getting-started-5-min-examples)
+
+- :material-cogs: **Core Workflows**
+ ---
+ Common workflows for building production-ready graphs.
+
+ [View Examples](#core-workflows-15-min-examples)
-!!! note "Prerequisites"
- All examples assume you have Semantica installed. See the [Installation Guide](installation.md) if you need to set it up first.
+- :material-rocket: **Advanced Patterns**
+ ---
+ Complex use cases and production deployments.
+
+ [View Examples](#advanced-patterns-30-min-examples)
+
+- :material-factory: **Production Patterns**
+ ---
+ Scalable deployment patterns for enterprise use.
+
+ [View Examples](#production-patterns)
+
+</div>
---
## Getting Started (5 min examples)
-Quick examples to get you up and running with Semantica.
-
### Example 1: Basic Knowledge Graph
-**Difficulty**: Beginner
-**Time**: 5 minutes
-**Prerequisites**: Semantica installed, sample PDF
+**Difficulty**: Beginner | **Time**: 5 min
Build a knowledge graph from a single document.
-**Code**:
-
```python
from semantica import Semantica
@@ -52,193 +64,74 @@ print(f"Entities: {len(kg['entities'])}")
print(f"Relationships: {len(kg['relationships'])}")
```
-**Expected Output**:
-
-```
-Entities: 45
-Relationships: 32
-```
-
-**Common Errors**:
-
-- `FileNotFoundError`: Ensure the PDF file exists in the current directory
-- `ImportError`: Make sure Semantica is installed: `pip install semantica`
-
-**Next Steps**:
-
-- [Example 2: Entity Extraction](#example-2-entity-extraction)
-- [Core Workflows](#core-workflows-15-min-examples)
-
----
-
### Example 2: Entity Extraction
-**Difficulty**: Beginner
-**Time**: 5 minutes
-**Prerequisites**: Semantica installed
+**Difficulty**: Beginner | **Time**: 5 min
Extract entities from text using Named Entity Recognition.
-**Code**:
-
```python
from semantica import Semantica
semantica = Semantica()
-
-text = """
-Apple Inc. is a technology company founded by Steve Jobs.
-The company is headquartered in Cupertino, California.
-Tim Cook is the current CEO of Apple.
-"""
+text = "Apple Inc. is a technology company founded by Steve Jobs."
entities = semantica.semantic_extract.extract_entities(text)
for entity in entities["entities"]:
print(f"{entity['text']}: {entity['type']}")
```
-**Expected Output**:
-
-```
-Apple Inc.: ORGANIZATION
-Steve Jobs: PERSON
-Cupertino: LOCATION
-California: LOCATION
-Tim Cook: PERSON
-```
-
-**Common Errors**:
-
-- `AttributeError`: Ensure you're using the correct API: `semantica.semantic_extract.extract_entities()`
-- Empty results: Check that your text contains named entities
-
-**Next Steps**:
-
-- [Example 3: Multi-Source Integration](#example-3-multi-source-integration)
-- [Core Workflows](#core-workflows-15-min-examples)
-
----
-
### Example 3: Multi-Source Integration
-**Difficulty**: Beginner
-**Time**: 5 minutes
-**Prerequisites**: Multiple data sources
+**Difficulty**: Beginner | **Time**: 5 min
Combine data from multiple sources into a unified knowledge graph.
-**Code**:
-
```python
from semantica import Semantica
semantica = Semantica()
-
sources = [
"documents/finance_report.pdf",
- "documents/market_analysis.docx",
"https://example.com/news-article"
]
result = semantica.build_knowledge_base(sources)
-kg = result["knowledge_graph"]
-
-print(f"Unified knowledge graph with {len(kg['entities'])} entities")
-```
-
-**Expected Output**:
-
-```
-Unified knowledge graph with 120 entities
-```
-
-**Common Errors**:
-
-- Network errors for URLs: Check internet connection and URL accessibility
-- File format errors: Ensure all file formats are supported
-
-**Next Steps**:
-
-- [Core Workflows](#core-workflows-15-min-examples)
-
----
-
-### Example 4: Export Formats
-
-**Difficulty**: Beginner
-**Time**: 5 minutes
-**Prerequisites**: Knowledge graph built
-
-Export knowledge graph to multiple formats.
-
-**Code**:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-kg = semantica.kg.build_graph(["data.pdf"])
-
-# Export to different formats
-semantica.export.to_rdf(kg, "output.rdf")
-semantica.export.to_json(kg, "output.json")
-semantica.export.to_csv(kg, "output.csv")
-semantica.export.to_owl(kg, "output.owl")
+print(f"Unified graph: {len(result['knowledge_graph']['entities'])} entities")
```
---
## Core Workflows (15 min examples)
-Common workflows for building production-ready knowledge graphs.
-
-### Example 5: Conflict Resolution
+### Example 4: Conflict Resolution
-**Difficulty**: Intermediate
-**Time**: 15 minutes
-**Prerequisites**: Multiple data sources with potential conflicts
+**Difficulty**: Intermediate | **Time**: 15 min
Resolve conflicts in data from multiple sources.
-**Code**:
-
```python
from semantica import Semantica
from semantica.conflicts import ConflictResolver
semantica = Semantica()
+result = semantica.build_knowledge_base(["source1.pdf", "source2.pdf"])
-# Build graph from multiple sources
-result = semantica.build_knowledge_base([
- "source1.pdf",
- "source2.pdf",
- "source3.pdf"
-])
-
-# Detect conflicts
+# Detect and resolve conflicts
conflicts = semantica.kg.detect_conflicts(result["knowledge_graph"])
-
-# Resolve conflicts
resolver = ConflictResolver(default_strategy="voting")
resolved = resolver.resolve_conflicts(conflicts)
-
-print(f"Resolved {len(resolved)} conflicts")
```
-### Example 6: Custom Configuration
+### Example 5: Custom Configuration
-**Difficulty**: Intermediate
-**Time**: 15 minutes
-**Prerequisites**: Understanding of configuration options
+**Difficulty**: Intermediate | **Time**: 15 min
Use custom configuration for specific use cases.
-**Code**:
-
```python
from semantica import Semantica, Config
-# Custom configuration
config = Config(
embeddings=True,
graph=True,
@@ -250,16 +143,12 @@ semantica = Semantica(config=config)
result = semantica.build_knowledge_base(["document.pdf"])
```
-### Example 7: Incremental Graph Building
+### Example 6: Incremental Graph Building
-**Difficulty**: Intermediate
-**Time**: 15 minutes
-**Prerequisites**: Multiple data sources to process incrementally
+**Difficulty**: Intermediate | **Time**: 15 min
Build knowledge graph incrementally.
-**Code**:
-
```python
from semantica import Semantica
@@ -268,57 +157,20 @@ semantica = Semantica()
# Build graphs separately
kg1 = semantica.kg.build_graph(["source1.pdf"])
kg2 = semantica.kg.build_graph(["source2.pdf"])
-kg3 = semantica.kg.build_graph(["source3.pdf"])
# Merge into unified graph
-merged_kg = semantica.kg.merge([kg1, kg2, kg3])
-
-print(f"Merged graph: {len(merged_kg['entities'])} entities")
-```
-
-### Example 8: Visualization
-
-**Difficulty**: Beginner
-**Time**: 10 minutes
-**Prerequisites**: Knowledge graph built
-
-Create interactive visualizations.
-
-**Code**:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-
-# Build graph
-result = semantica.build_knowledge_base(["document.pdf"])
-kg = result["knowledge_graph"]
-
-# Visualize
-semantica.kg.visualize(kg, output_path="graph.html")
-
-# Also analyze
-analysis = semantica.kg.analyze(kg)
-print(f"Graph density: {analysis['density']}")
-print(f"Connected components: {analysis['components']}")
+merged_kg = semantica.kg.merge([kg1, kg2])
```
---
## Advanced Patterns (30+ min examples)
-Advanced patterns for complex use cases and production deployments.
+### Example 7: Graph Store (Persistent Storage)
-### Example 9: Graph Store (Persistent Storage)
+**Difficulty**: Intermediate | **Time**: 30 min
-**Difficulty**: Intermediate
-**Time**: 30 minutes
-**Prerequisites**: Neo4j or KuzuDB installed
-
-Store and query knowledge graphs in a persistent graph database.
-
-**Code**:
+Store and query knowledge graphs in a persistent graph database like Neo4j.
```python
from semantica.graph_store import GraphStore
@@ -332,75 +184,23 @@ store = GraphStore(
)
store.connect()
-# Create nodes
-apple = store.create_node(
- labels=["Company"],
- properties={"name": "Apple Inc.", "founded": 1976}
-)
-
-tim_cook = store.create_node(
- labels=["Person"],
- properties={"name": "Tim Cook", "title": "CEO"}
-)
-
-# Create relationship
-store.create_relationship(
- start_node_id=tim_cook["id"],
- end_node_id=apple["id"],
- rel_type="CEO_OF",
- properties={"since": 2011}
-)
-
-# Query with Cypher
-results = store.execute_query("""
- MATCH (p:Person)-[:CEO_OF]->(c:Company)
- RETURN p.name, c.name
-""")
-
-print(f"Query results: {results}")
-store.close()
-```
-
-### Example 10: Using KuzuDB (Embedded)
-
-**Difficulty**: Intermediate
-**Time**: 20 minutes
-**Prerequisites**: KuzuDB installed
-
-For embedded graph storage without external dependencies.
-
-**Code**:
-
-```python
-from semantica.graph_store import GraphStore
-
-# KuzuDB - no server required
-store = GraphStore(backend="kuzu", database_path="./my_graph_db")
-store.connect()
-
-# Store your knowledge graph
-node = store.create_node(["Entity"], {"name": "Test"})
-neighbors = store.get_neighbors(node["id"], depth=2)
-stats = store.get_stats()
+# Create nodes and relationships
+apple = store.create_node(["Company"], {"name": "Apple Inc."})
+tim = store.create_node(["Person"], {"name": "Tim Cook"})
+store.create_relationship(tim["id"], apple["id"], "CEO_OF")
-print(f"Graph stats: {stats}")
store.close()
```
-### Example 11: FalkorDB for Real-Time Applications
-
-**Difficulty**: Intermediate
-**Time**: 25 minutes
-**Prerequisites**: Redis and FalkorDB installed
+### Example 8: FalkorDB for Real-Time Applications
-Ultra-fast graph queries for LLM applications.
+**Difficulty**: Intermediate | **Time**: 25 min
-**Code**:
+Ultra-fast graph queries for LLM applications using FalkorDB.
```python
from semantica.graph_store import GraphStore
-# FalkorDB - Redis-based, ultra-fast
store = GraphStore(
backend="falkordb",
host="localhost",
@@ -409,13 +209,8 @@ store = GraphStore(
)
store.connect()
-# Fast queries for RAG applications
-results = store.execute_query("""
- MATCH (n)-[r]->(m)
- WHERE n.name CONTAINS $query
- RETURN n, r, m LIMIT 10
-""", parameters={"query": "AI"})
-
+# Fast queries
+results = store.execute_query("MATCH (n)-[r]->(m) WHERE n.name CONTAINS 'AI' RETURN n")
store.close()
```
@@ -423,87 +218,36 @@ store.close()
## Production Patterns
-Production-ready patterns for scalable deployments.
-
-### Example 12: Streaming Data Processing
+### Example 9: Streaming Data Processing
-**Difficulty**: Advanced
-**Time**: 45 minutes
-**Prerequisites**: Understanding of streaming architectures
+**Difficulty**: Advanced | **Time**: 45 min
Process data streams in real-time.
-**Code**:
-
```python
from semantica.ingest import StreamIngestor
from semantica import Semantica
semantica = Semantica()
-
-# Set up stream ingestor
stream_ingestor = StreamIngestor(stream_uri="kafka://localhost:9092/topic")
-# Process stream
for batch in stream_ingestor.stream(batch_size=100):
result = semantica.build_knowledge_base(
sources=batch,
embeddings=True,
graph=True
)
- # Process and store results
- process_results(result)
-```
-
-**Expected Output**:
-```
-Processing batch 1: 100 documents
-Processing batch 2: 100 documents
-...
-```
-
----
-
-### Example 13: Custom Extractors
-
-**Difficulty**: Advanced
-**Time**: 60 minutes
-**Prerequisites**: Understanding of extraction patterns
-
-Create custom entity extractors for domain-specific entities.
-
-**Code**:
-
-```python
-from semantica.semantic_extract import BaseExtractor
-
-class CustomProductExtractor(BaseExtractor):
- def extract(self, text):
- # Your custom extraction logic
- products = []
- # Pattern matching or ML model
- return products
-
-# Use custom extractor
-extractor = CustomProductExtractor()
-entities = extractor.extract(text)
+ # Process results
```
----
+### Example 10: Batch Processing Large Datasets
-### Example 14: Batch Processing Large Datasets
-
-**Difficulty**: Intermediate
-**Time**: 30 minutes
-**Prerequisites**: Large dataset to process
+**Difficulty**: Intermediate | **Time**: 30 min
Process large datasets efficiently with batching.
-**Code**:
-
```python
from semantica import Semantica
-import os
semantica = Semantica()
sources = [f"data/doc_{i}.pdf" for i in range(1000)]
@@ -511,110 +255,10 @@ batch_size = 50
for i in range(0, len(sources), batch_size):
batch = sources[i:i+batch_size]
- result = semantica.build_knowledge_base(
- sources=batch,
- embeddings=True,
- graph=True
- )
+ result = semantica.build_knowledge_base(batch)
# Save intermediate results
- save_batch_result(result, batch_num=i//batch_size)
-```
-
----
-
-## Use Case Examples
-
-### Research Paper Analysis
-
-Extract knowledge from research papers:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-
-# Process research paper
-result = semantica.build_knowledge_base([
- "papers/ai_research.pdf",
- "papers/ml_survey.pdf"
-])
-
-kg = result["knowledge_graph"]
-
-# Find key concepts
-concepts = [e for e in kg["entities"] if e["type"] == "CONCEPT"]
-print(f"Found {len(concepts)} key concepts")
-```
-
-### Company Intelligence
-
-Build knowledge graph from company documents:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-
-# Company documents
-sources = [
- "company/annual_report.pdf",
- "company/press_releases/",
- "company/website_content.html"
-]
-
-result = semantica.build_knowledge_base(sources)
-kg = result["knowledge_graph"]
-
-# Export for analysis
-semantica.export.to_json(kg, "company_intelligence.json")
-```
-
-### News Article Processing
-
-Process and analyze news articles:
-
-```python
-from semantica import Semantica
-
-semantica = Semantica()
-
-# News articles
-articles = [
- "https://example.com/article1",
- "https://example.com/article2",
- "https://example.com/article3"
-]
-
-result = semantica.build_knowledge_base(articles)
-kg = result["knowledge_graph"]
-
-# Extract key entities
-people = [e for e in kg["entities"] if e["type"] == "PERSON"]
-organizations = [e for e in kg["entities"] if e["type"] == "ORGANIZATION"]
-
-print(f"People mentioned: {len(people)}")
-print(f"Organizations: {len(organizations)}")
```
-## Interactive Examples
-
-For more interactive examples and tutorials, check out our [Cookbook](cookbook.md) with Jupyter notebooks covering:
-
-- **Introduction**: Getting started tutorials
-- **Advanced**: Advanced techniques and patterns
-- **Use Cases**: Real-world applications in various domains
-
----
-
-## Example Gallery
-
-Visual previews of what you can build with Semantica:
-
-- **Knowledge Graph Visualization**: Interactive network graphs
-- 📈 **Analytics Dashboards**: Quality metrics and insights
-- 🔍 **Semantic Search**: Vector-based document retrieval
-- 🧠 **GraphRAG Applications**: Enhanced LLM responses
-
---
## More Resources
@@ -623,7 +267,6 @@ Visual previews of what you can build with Semantica:
- **[API Reference](reference/core.md)** - Complete API documentation
- **[Cookbook](cookbook.md)** - Interactive Jupyter notebooks
- **[Use Cases](use-cases.md)** - Real-world applications
-- **[Modules Guide](modules.md)** - Module documentation
---
diff --git a/docs/learning-more.md b/docs/learning-more.md
index 7e6b6488..75f4dd74 100644
--- a/docs/learning-more.md
+++ b/docs/learning-more.md
@@ -7,173 +7,115 @@ Additional resources, tutorials, and advanced learning materials for Semantica.
---
-## Table of Contents
+## Structured Learning Paths
-- [Structured Learning Paths](#structured-learning-paths)
-- [Quick Reference](#quick-reference)
-- [Troubleshooting Guide](#troubleshooting-guide)
-- [Migration Guide](#migration-guide)
-- [Performance Optimization](#performance-optimization)
-- [Security Best Practices](#security-best-practices)
-- [FAQ Expansion](#faq-expansion)
-- [Glossary Quick Reference](#glossary-quick-reference)
+<div class="grid cards" markdown>
+
+- :material-school: **Beginner Path**
+ ---
+ Perfect for those new to Semantica and knowledge graphs.
+
+ **Time**: 1-2 hours
+
+ [Start Path](#beginner-path-1-2-hours)
+
+- :material-compass: **Intermediate Path**
+ ---
+ For users comfortable with basics who want to build production applications.
+
+ **Time**: 4-6 hours
+
+ [Start Path](#intermediate-path-4-6-hours)
+
+- :material-rocket: **Advanced Path**
+ ---
+ For experienced users building enterprise applications.
+
+ **Time**: 8+ hours
+
+ [Start Path](#advanced-path-8-hours)
+
+</div>
---
-## Structured Learning Paths
-
-Follow these structured paths based on your experience level.
-
### Beginner Path (1-2 hours)
-Perfect for those new to Semantica and knowledge graphs.
-
-**Step 1: Installation & Setup** (15 min)
-- [Installation Guide](installation.md)
-- [Configuration Basics](cookbook/introduction/Configuration_Basics.ipynb)
-- Verify installation: `import semantica; print(semantica.__version__)`
+1. **Installation & Setup** (15 min)
+ - [Installation Guide](installation.md)
+ - [Configuration Basics](cookbook/introduction/Configuration_Basics.ipynb)
-**Step 2: Core Concepts** (30 min)
-- [Core Concepts](concepts.md) - Read sections 1-5
-- [Getting Started Guide](getting-started.md)
-- Understand: Knowledge Graphs, Entities, Relationships
+2. **Core Concepts** (30 min)
+ - [Core Concepts](concepts.md)
+ - [Getting Started Guide](getting-started.md)
-**Step 3: First Knowledge Graph** (30 min)
-- [Quickstart Tutorial](quickstart.md)
-- [Your First Knowledge Graph](cookbook/introduction/Your_First_Knowledge_Graph.ipynb)
-- Build a simple KG from a document
+3. **First Knowledge Graph** (30 min)
+ - [Quickstart Tutorial](quickstart.md)
+ - [Your First Knowledge Graph](cookbook/introduction/Your_First_Knowledge_Graph.ipynb)
-**Step 4: Basic Operations** (30 min)
-- [Examples](examples.md) - Examples 1-3
-- Extract entities and relationships
-- Visualize your graph
-
-**Completion Checklist**:
-- Semantica installed and configured
-- Built your first knowledge graph
-- Understand basic concepts
-- Can extract entities and relationships
-
-**Next**: Move to [Intermediate Path](#intermediate-path-4-6-hours)
+4. **Basic Operations** (30 min)
+ - [Examples](examples.md)
+ - Extract entities and relationships
---
### Intermediate Path (4-6 hours)
-For users comfortable with basics who want to build production applications.
-
-**Step 1: Advanced Concepts** (1 hour)
-- [Core Concepts](concepts.md) - Complete guide
-- [Modules Guide](modules.md) - All 13 modules
-- Understand: Embeddings, GraphRAG, Ontologies
-
-**Step 2: Use Cases** (1 hour)
-- [Use Cases Guide](use-cases.md)
-- Pick 2-3 relevant use cases
-- Implement at least one complete use case
-
-**Step 3: Advanced Examples** (1 hour)
-- [Examples](examples.md) - Examples 4-10
-- Conflict resolution
-- Custom configuration
-- Graph stores
+1. **Advanced Concepts** (1 hour)
+ - [Modules Guide](modules.md)
+ - Understand: Embeddings, GraphRAG, Ontologies
-**Step 4: Quality & Optimization** (1 hour)
-- [Quality Assurance](concepts.md#8-quality-assurance)
-- [Performance Optimization](#performance-optimization)
-- Learn about deduplication and conflict detection
+2. **Use Cases** (1 hour)
+ - [Use Cases Guide](use-cases.md)
+ - Implement a complete use case
-**Step 5: Integration Patterns** (1 hour)
-- [Integration Patterns](modules.md#integration-patterns)
-- Build a complete pipeline
-- Connect multiple modules
+3. **Advanced Examples** (1 hour)
+ - [Examples](examples.md) - Conflict resolution, custom config
-**Completion Checklist**:
-- Understand all core concepts
-- Can build complex knowledge graphs
-- Know how to optimize performance
-- Can integrate multiple modules
-- Implemented a real-world use case
-
-**Next**: Move to [Advanced Path](#advanced-path-8-hours)
+4. **Quality & Optimization** (1 hour)
+ - [Quality Assurance](concepts.md#8-quality-assurance)
+ - [Performance Optimization](#performance-optimization)
---
### Advanced Path (8+ hours)
-For experienced users building enterprise applications.
-
-**Step 1: Advanced Architecture** (2 hours)
-- [Architecture Guide](architecture.md)
-- [Deep Dive](deep-dive.md)
-- Custom extractors and exporters
-- Plugin development
-
-**Step 2: Production Deployment** (2 hours)
-- [Performance Optimization](#performance-optimization)
-- [Security Best Practices](#security-best-practices)
-- Scalability patterns
-- Monitoring and logging
-
-**Step 3: Advanced Use Cases** (2 hours)
-- [Use Cases](use-cases.md) - All advanced use cases
-- [Examples](examples.md) - Production patterns
-- Build a complete production system
-
-**Step 4: Customization** (2 hours)
-- Custom extractors
-- Custom exporters
-- Plugin development
-- API extensions
-
-**Completion Checklist**:
-- Can design custom architectures
-- Understand production deployment
-- Can build custom components
-- Have implemented a production system
+1. **Advanced Architecture** (2 hours)
+ - [Architecture Guide](architecture.md)
+ - Plugin development
+
+2. **Production Deployment** (2 hours)
+ - [Security Best Practices](#security-best-practices)
+ - Scalability patterns
+
+3. **Customization** (2 hours)
+ - Custom extractors and exporters
+ - API extensions
---
## Quick Reference
-### Common Operations Cheat Sheet
+### Common Operations
-**Initialize Semantica**:
```python
from semantica import Semantica
semantica = Semantica()
-```
-**Build Knowledge Graph**:
-```python
+# Build Knowledge Graph
result = semantica.build_knowledge_base(
sources=["doc.pdf"],
embeddings=True,
graph=True
)
-```
-**Extract Entities**:
-```python
+# Extract Entities
entities = semantica.semantic_extract.extract_entities(text)
-```
-**Extract Relationships**:
-```python
-relationships = semantica.semantic_extract.extract_relations(text, entities)
-```
-
-**Query Graph**:
-```python
+# Query Graph
results = semantica.kg.query("MATCH (n) RETURN n LIMIT 10")
```
-**Export Graph**:
-```python
-semantica.export.to_json(kg, "output.json")
-semantica.export.to_rdf(kg, "output.rdf")
-```
-
### Configuration Reference
| Setting | Environment Variable | Config File | Default |
@@ -181,243 +123,57 @@ semantica.export.to_rdf(kg, "output.rdf")
| OpenAI API Key | `OPENAI_API_KEY` | `api_keys.openai` | `None` |
| Embedding Provider | `SEMANTICA_EMBEDDING_PROVIDER` | `embedding.provider` | `"openai"` |
| Graph Backend | `SEMANTICA_GRAPH_BACKEND` | `knowledge_graph.backend` | `"networkx"` |
-| Temporal Graphs | `SEMANTICA_TEMPORAL` | `knowledge_graph.temporal` | `False` |
-
-### CLI Commands Reference
-
-```bash
-# Install Semantica
-pip install semantica
-
-# Install with extras
-pip install semantica[all]
-pip install semantica[gpu]
-pip install semantica[visualization]
-
-# Verify installation
-python -c "import semantica; print(semantica.__version__)"
-
-# Run tests
-pytest tests/
-
-# Build documentation
-mkdocs serve
-```
---
## Troubleshooting Guide
-### Common Issues and Solutions
-
-#### Issue: Import Errors
-
-**Symptoms**: `ModuleNotFoundError` or `ImportError`
-
-**Solutions**:
-1. Verify installation: `pip list | grep semantica`
-2. Check Python version: `python --version` (requires 3.8+)
-3. Reinstall: `pip install --upgrade semantica`
-4. Check virtual environment is activated
-
-**Code**:
-```python
-import sys
-print(sys.version) # Should be 3.8+
-import semantica
-print(semantica.__version__)
-```
-
-#### Issue: API Key Errors
-
-**Symptoms**: `AuthenticationError` or `Invalid API Key`
-
-**Solutions**:
-1. Set environment variable: `export OPENAI_API_KEY=your_key`
-2. Check config file: `~/.semantica/config.yaml`
-3. Verify key is valid: Test with OpenAI API directly
-4. Check key has sufficient credits
-
-**Code**:
-```python
-import os
-print(os.getenv("OPENAI_API_KEY")) # Should not be None
-```
-
-#### Issue: Memory Errors
-
-**Symptoms**: `MemoryError` or system slowdown
-
-**Solutions**:
-1. Process in smaller batches
-2. Use graph stores (Neo4j, KuzuDB) instead of NetworkX
-3. Reduce batch sizes
-4. Enable garbage collection
-5. Use streaming for large datasets
-
-**Code**:
-```python
-# Process in batches
-batch_size = 10
-for i in range(0, len(sources), batch_size):
- batch = sources[i:i+batch_size]
- result = semantica.build_knowledge_base(batch)
-```
-
-#### Issue: Slow Processing
-
-**Symptoms**: Very long processing times
-
-**Solutions**:
-1. Enable parallel processing
-2. Use faster embedding models
-3. Cache embeddings
-4. Use GPU acceleration
-5. Optimize batch sizes
-
-**Code**:
-```python
-# Enable parallel processing
-result = semantica.build_knowledge_base(
- sources=sources,
- parallel=True,
- max_workers=4
-)
-```
-
-#### Issue: Low Quality Extractions
-
-**Symptoms**: Incorrect or missing entities/relationships
-
-**Solutions**:
-1. Use LLM-based extraction (more accurate)
-2. Preprocess and normalize text
-3. Adjust confidence thresholds
-4. Use domain-specific models
-5. Validate and clean extracted data
-
-**Code**:
-```python
-# Use LLM-based extraction
-extractor = NERExtractor(method="llm", model="gpt-4")
-entities = extractor.extract(text)
-```
-
-#### Issue: Graph Too Large
-
-**Symptoms**: Memory issues, slow queries
-
-**Solutions**:
-1. Use graph store backends (Neo4j, KuzuDB)
-2. Filter by confidence threshold
-3. Implement graph partitioning
-4. Use incremental building
-5. Remove low-value relationships
-
-**Code**:
-```python
-# Use Neo4j for large graphs
-builder = GraphBuilder(backend="neo4j")
-kg = builder.build(entities, relationships)
-```
-
----
-
-## Migration Guide
-
-### Migrating from Other Tools
-
-#### From NetworkX
-
-**Key Differences**:
-- Semantica provides higher-level abstractions
-- Built-in entity extraction and relationship extraction
-- Integrated embeddings and vector stores
+<div class="grid cards" markdown>
-**Migration Steps**:
-1. Install Semantica: `pip install semantica`
-2. Convert existing graphs to Semantica format
-3. Use Semantica's extraction capabilities
-4. Migrate to Semantica's graph stores
+- :material-alert: **Import Errors**
+ ---
+ `ModuleNotFoundError`
+
+ **Solution**: Verify installation (`pip list`) and Python version (3.8+).
-**Code**:
-```python
-# Old: NetworkX
-import networkx as nx
-G = nx.DiGraph()
-G.add_node("entity1")
-G.add_edge("entity1", "entity2", relation="knows")
-
-# New: Semantica
-from semantica import Semantica
-semantica = Semantica()
-result = semantica.build_knowledge_base(["doc.pdf"])
-kg = result["knowledge_graph"]
-```
+- :material-key: **API Key Errors**
+ ---
+ `AuthenticationError`
+
+ **Solution**: Set `OPENAI_API_KEY` environment variable.
-#### From spaCy
+- :material-memory: **Memory Errors**
+ ---
+ `MemoryError`
+
+ **Solution**: Use batch processing and graph stores (Neo4j).
-**Key Differences**:
-- Semantica includes graph construction
-- Integrated knowledge graph management
-- Built-in relationship extraction
+- :material-speedometer: **Slow Processing**
+ ---
+ Long processing times
+
+ **Solution**: Enable parallel processing and GPU acceleration.
-**Migration Steps**:
-1. Replace spaCy NER with Semantica's extractors
-2. Use Semantica's relationship extraction
-3. Build knowledge graphs automatically
-
-**Code**:
-```python
-# Old: spaCy
-import spacy
-nlp = spacy.load("en_core_web_sm")
-doc = nlp(text)
-entities = [(ent.text, ent.label_) for ent in doc.ents]
-
-# New: Semantica
-from semantica import Semantica
-semantica = Semantica()
-entities = semantica.semantic_extract.extract_entities(text)
-kg = semantica.build_knowledge_base([text])
-```
+</div>
---
## Performance Optimization
-### Optimization Strategies
-
-#### 1. Batch Processing
+### 1. Batch Processing
Process multiple documents together for better throughput.
```python
-# Good: Batch processing
sources = ["doc1.pdf", "doc2.pdf", ..., "doc100.pdf"]
result = semantica.build_knowledge_base(sources, batch_size=10)
-
-# Bad: One at a time
-for source in sources:
- result = semantica.build_knowledge_base([source])
-```
-
-#### 2. Caching
-
-Cache expensive operations like embeddings.
-
-```python
-# Enable caching
-generator = EmbeddingGenerator(cache=True)
-embeddings = generator.generate(texts) # Cached on second call
```
-#### 3. Parallel Execution
+### 2. Parallel Execution
Use parallel processing for independent operations.
```python
-# Enable parallel processing
result = semantica.build_knowledge_base(
sources=sources,
parallel=True,
@@ -425,41 +181,13 @@ result = semantica.build_knowledge_base(
)
```
-#### 4. Backend Selection
-
-Choose appropriate backends for your scale.
+### 3. Backend Selection
-```python
-# Small graphs: NetworkX (fast, in-memory)
-builder = GraphBuilder(backend="networkx")
-
-# Large graphs: Neo4j (persistent, scalable)
-builder = GraphBuilder(backend="neo4j")
-```
-
-#### 5. Resource Limits
-
-Set appropriate limits to prevent resource exhaustion.
-
-```python
-# Limit memory usage
-parser = DocumentParser(max_file_size=10_000_000) # 10MB
-
-# Limit processing time
-result = semantica.build_knowledge_base(
- sources=sources,
- timeout=300 # 5 minutes
-)
-```
-
-### Performance Benchmarks
-
-| Operation | NetworkX | Neo4j | KuzuDB | Notes |
-| :--- | :--- | :--- | :--- | :--- |
-| **Graph Construction** | ⚡⚡⚡ | ⚡⚡ | ⚡⚡⚡ | NetworkX fastest for small graphs |
-| **Query Performance** | ⚡⚡ | ⚡⚡⚡ | ⚡⚡⚡ | Neo4j/KuzuDB better for complex queries |
-| **Memory Usage** | High | Low | Medium | NetworkX loads all in memory |
-| **Scalability** | Low | High | Medium | Neo4j best for large graphs |
+| Operation | NetworkX | Neo4j | KuzuDB |
+| :--- | :--- | :--- | :--- |
+| **Graph Construction** | ⚡⚡⚡ | ⚡⚡ | ⚡⚡⚡ |
+| **Query Performance** | ⚡⚡ | ⚡⚡⚡ | ⚡⚡⚡ |
+| **Scalability** | Low | High | Medium |
---
@@ -467,178 +195,38 @@ result = semantica.build_knowledge_base(
### API Key Management
-**DO**:
-- Use environment variables for API keys
-- Store keys in secure configuration files
-- Rotate keys regularly
-- Use separate keys for development/production
-
-**DON'T**:
-- Commit API keys to version control
-- Hardcode keys in source code
-- Share keys publicly
-- Use production keys in development
-
-**Code**:
-```python
-# Good: Environment variables
-import os
-api_key = os.getenv("OPENAI_API_KEY")
-
-# Bad: Hardcoded
-api_key = "sk-..." # Never do this!
-```
+- **DO**: Use environment variables, rotate keys regularly.
+- **DON'T**: Hardcode keys, commit to version control.
### Data Privacy
-**DO**:
-- Encrypt sensitive data
-- Use local models when possible
-- Implement access controls
-- Audit data access
-
-**DON'T**:
-- Send sensitive data to external APIs without encryption
-- Store PII in knowledge graphs without protection
-- Share knowledge graphs with sensitive data
-
-### Network Security
-
-**DO**:
-- Use HTTPS for all API calls
-- Validate SSL certificates
-- Implement rate limiting
-- Monitor for suspicious activity
-
-**DON'T**:
-- Use HTTP for API calls
-- Disable SSL verification
-- Ignore security warnings
+- **DO**: Encrypt sensitive data, use local models.
+- **DON'T**: Send PII to external APIs without protection.
---
-## FAQ Expansion
-
-### General Questions
+## FAQ
**Q: What is Semantica?**
-A: Semantica is a comprehensive framework for building knowledge graphs and semantic applications. It provides tools for entity extraction, relationship extraction, graph construction, and more.
-
-**Q: Do I need to know graph theory?**
-A: No, but basic understanding helps. Semantica abstracts away most complexity.
+A: A framework for building knowledge graphs and semantic applications.
**Q: Is Semantica free?**
-A: Yes, Semantica is open source. However, some features require paid API access (e.g., OpenAI for embeddings).
-
-### Technical Questions
-
-**Q: What Python version do I need?**
-A: Python 3.8 or higher.
-
-**Q: Can I use Semantica without external APIs?**
-A: Yes, but with limited functionality. You can use local models for some operations.
-
-**Q: How do I handle large datasets?**
-A: Use batch processing, graph stores (Neo4j, KuzuDB), and parallel execution.
-
-**Q: Can I customize entity extraction?**
-A: Yes, you can create custom extractors by extending `BaseExtractor`.
-
-### Performance Questions
-
-**Q: How fast is Semantica?**
-A: Depends on your setup. With proper optimization, it can process thousands of documents per hour.
-
-**Q: How much memory does it use?**
-A: Varies by graph size. Use graph stores for large graphs to reduce memory usage.
-
-**Q: Can I use GPU acceleration?**
-A: Yes, for some operations like embeddings. Install with `pip install semantica[gpu]`.
-
-### Integration Questions
-
-**Q: Can I use Semantica with other tools?**
-A: Yes, Semantica exports to many formats (JSON, RDF, CSV, OWL) and integrates with various databases.
-
-**Q: Does Semantica work with LangChain?**
-A: Yes, you can integrate Semantica with LangChain for RAG applications.
+A: Yes, it is open source. Some features (e.g., OpenAI) require paid APIs.
**Q: Can I use Semantica in production?**
-A: Yes, Semantica is designed for production use with proper configuration and monitoring.
-
----
-
-## Glossary Quick Reference
-
-Quick reference for common terms. See [Full Glossary](glossary.md) for complete definitions.
-
-| Term | Definition |
-| :--- | :--- |
-| **Entity** | A distinct object or concept (person, place, organization) |
-| **Relationship** | A connection between entities |
-| **Knowledge Graph** | A structured representation of entities and relationships |
-| **Embedding** | A vector representation of text or data |
-| **NER** | Named Entity Recognition - identifying entities in text |
-| **GraphRAG** | Graph-Augmented Retrieval Augmented Generation |
-| **Ontology** | A formal specification of concepts and relationships |
-| **Temporal Graph** | A knowledge graph that tracks changes over time |
-| **Deduplication** | Identifying and merging duplicate entities |
-| **Conflict Resolution** | Handling contradictory information |
-
-**See Also**: [Full Glossary](glossary.md) | [Core Concepts](concepts.md)
-
----
-
-## Additional Resources
-
-### Video Tutorials
-
-Coming soon! We're working on video tutorials covering:
-- Getting started with Semantica
-- Building your first knowledge graph
-- Advanced techniques and patterns
-- Real-world use cases
-
-### Blog Posts & Articles
-
-Stay tuned for blog posts covering:
-- Best practices for knowledge graph construction
-- Performance optimization tips
-- Integration guides
-- Case studies and success stories
-
-### Community Resources
-
-**GitHub Discussions**:
-- [General Discussion](https://github.com/Hawksight-AI/semantica/discussions)
-- [Q&A](https://github.com/Hawksight-AI/semantica/discussions/categories/q-a)
-- [Show and Tell](https://github.com/Hawksight-AI/semantica/discussions/categories/show-and-tell)
-
-**Contributing**:
-- [Contributing Guide](https://github.com/Hawksight-AI/semantica/blob/main/CONTRIBUTING.md)
-- [Examples Repository](https://github.com/Hawksight-AI/semantica/tree/main/examples)
-
-### Related Projects
-
-**GraphRAG**: Semantica works great with GraphRAG implementations. See our [GraphRAG examples](cookbook.md#advanced-rag).
-
-**Vector Databases**: Integrate with Pinecone, Weaviate, Qdrant, Milvus.
-
-**Knowledge Graph Databases**: Export to Neo4j, Amazon Neptune, ArangoDB, Blazegraph.
+A: Yes, it is designed for production with proper configuration.
---
## Next Steps
-- **[Deep Dive](deep-dive.md)** - Advanced architecture and internals
+- **[Deep Dive](deep-dive.md)** - Advanced architecture
- **[API Reference](reference/core.md)** - Complete API documentation
- **[Cookbook](cookbook.md)** - Interactive tutorials
-- **[Examples](examples.md)** - More code examples
-- **[Use Cases](use-cases.md)** - Real-world applications
---
!!! info "Contribute"
- Have questions or suggestions? [Open an issue](https://github.com/Hawksight-AI/semantica/issues) or [start a discussion](https://github.com/Hawksight-AI/semantica/discussions)!
+ Have questions? [Open an issue](https://github.com/Hawksight-AI/semantica/issues) or [start a discussion](https://github.com/Hawksight-AI/semantica/discussions)!
**Last Updated**: 2024
diff --git a/docs/modules.md b/docs/modules.md
index b1f4be58..096ca4dc 100644
--- a/docs/modules.md
+++ b/docs/modules.md
@@ -1,135 +1,29 @@
# Modules & Architecture
-Semantica is built with a modular architecture, designed to be flexible and extensible. This guide provides an overview of the key modules and their responsibilities.
+Semantica is built with a modular architecture, designed to be flexible, extensible, and scalable. This guide provides a comprehensive overview of the key modules, their responsibilities, and how they interact to build powerful semantic applications.
!!! info "About This Guide"
- This guide covers all 13 core modules in Semantica, their purposes, architecture, usage patterns, and how they integrate together.
+ This guide covers all 13 core modules in Semantica, organized by their functional layer. It details their purpose, key features, usage patterns, and configuration options.
---
-## Table of Contents
+## Module Overview
-- [Prerequisites](#prerequisites)
-- [Module Dependency Diagram](#module-dependency-diagram)
-- [Module Selection Guide](#module-selection-guide)
-- [Core Modules](#core-modules)
-- [Integration Patterns](#integration-patterns)
-- [Performance Considerations](#performance-considerations)
+Semantica's modules are organized into five logical layers. You can use these modules independently or combine them into a complete pipeline.
----
-
-## Prerequisites
-
-Before reading this guide, you should:
-
-- Understand basic Python programming
-- Be familiar with the [Core Concepts](concepts.md)
-- Have Semantica installed (see [Installation Guide](installation.md))
-- Understand basic data structures and algorithms
-
----
-
-## Module Dependency Diagram
-
-The following diagram shows how modules depend on and interact with each other:
-
-```mermaid
-graph TB
- subgraph Input["Input Layer"]
- Ingest[Ingest Module]
- Parse[Parse Module]
- Norm[Normalize Module]
- end
-
- subgraph Core["Core Processing"]
- Extract[Semantic Extract]
- KG[Knowledge Graph]
- Onto[Ontology]
- end
-
- subgraph Storage["Storage Layer"]
- VS[Vector Store]
- TS[Triple Store]
- GS[Graph Store]
- end
-
- subgraph Output["Output Layer"]
- Export[Export Module]
- Viz[Visualization]
- Reason[Reasoning]
- end
-
- subgraph Support["Support Modules"]
- Embed[Embeddings]
- Pipeline[Pipeline]
- end
-
- Ingest --> Parse
- Parse --> Norm
- Norm --> Extract
- Extract --> KG
- KG --> Onto
- KG --> VS
- KG --> TS
- KG --> GS
- Extract --> Embed
- Embed --> VS
- KG --> Export
- KG --> Viz
- KG --> Reason
- Onto --> KG
- Pipeline --> Ingest
- Pipeline --> Parse
- Pipeline --> Extract
- Pipeline --> KG
-
- style Ingest fill:#e1f5fe,stroke:#01579b
- style Extract fill:#e8f5e9,stroke:#1b5e20
- style KG fill:#fff3e0,stroke:#ef6c00,stroke-width:3px
- style VS fill:#f3e5f5,stroke:#7b1fa2
- style Pipeline fill:#ffebee,stroke:#c62828
-```
+| Layer | Modules | Description |
+| :--- | :--- | :--- |
+| **Input Layer** | [Ingest](#1-ingest-module), [Parse](#2-parse-module), [Normalize](#3-normalize-module) | Handles data ingestion, parsing, and cleaning from various sources. |
+| **Core Processing** | [Semantic Extract](#4-semantic-extract-module), [Knowledge Graph](#5-knowledge-graph-kg-module), [Ontology](#10-ontology-module), [Reasoning](#9-reasoning-module) | The "brain" of the system. Extracts meaning, builds graphs, and infers new knowledge. |
+| **Storage & Embeddings** | [Embeddings](#6-embeddings-module), [Vector Store](#7-vector-store-module), [Graph Store](#8-graph-store-module) | Manages persistent storage and retrieval of vectors and graphs. |
+| **Output Layer** | [Export](#11-export-module), [Visualization](#12-visualization-module) | Tools for visualizing data and exporting it to external systems. |
+| **Orchestration** | [Pipeline](#13-pipeline-module) | Manages workflows, execution, and resource scheduling. |
---
-## Module Selection Guide
-
-Use this flowchart to determine which modules you need for your use case:
-
-```mermaid
-flowchart TD
- Start[What do you want to do?] --> Q1{Process Documents?}
- Q1 -->|Yes| Ingest[Ingest, Parse, Normalize]
- Q1 -->|No| Q2{Extract Knowledge?}
-
- Q2 -->|Yes| Extract[Semantic Extract, KG]
- Q2 -->|No| Q3{Store Data?}
-
- Q3 -->|Vectors| VS[Embeddings, Vector Store]
- Q3 -->|Graph| GS[Graph Store]
- Q3 -->|Triples| TS[Triple Store]
- Q3 -->|No| Q4{Visualize?}
-
- Q4 -->|Yes| Viz[Visualization]
- Q4 -->|No| Q5{Export?}
-
- Q5 -->|Yes| Export[Export]
- Q5 -->|No| Q6{Reason/Infer?}
-
- Q6 -->|Yes| Reason[Reasoning]
- Q6 -->|No| Onto[Ontology]
-
- style Ingest fill:#e1f5fe
- style Extract fill:#e8f5e9
- style VS fill:#f3e5f5
- style GS fill:#fff3e0
-```
+## Input Layer
----
-
-## Core Modules
-
-Semantica is organized into 13 core modules. Below is a detailed breakdown of each.
+These modules are responsible for getting data into the system and preparing it for processing.
### 1. Ingest Module
@@ -207,15 +101,6 @@ mcp_docs = mcp_ingestor.ingest("https://your-mcp-server.com")
| `timeout` | `int` | `30` | Request timeout in seconds |
| `user_agent` | `str` | `None` | Custom user agent for web requests |
-**Common Use Cases**:
-
-- Processing document collections
-- Scraping websites for content
-- Extracting data from databases
-- Processing email archives
-- Real-time data streaming
-- Integrating with MCP servers
-
**API Reference**: [Ingest Module](reference/ingest.md)
### 2. Parse Module
@@ -279,13 +164,6 @@ for doc in parsed_docs:
| `extract_tables`| `bool` | `True` | Extract tables from documents |
| `extract_images`| `bool` | `False` | Extract and process images |
-**Common Use Cases**:
-- Extracting text from PDFs
-- Parsing spreadsheets
-- OCR from scanned documents
-- Extracting web content
-- Parsing code repositories
-
**API Reference**: [Parse Module](reference/parse.md)
### 3. Normalize Module
@@ -349,15 +227,14 @@ for doc in normalized:
| `normalize_numbers` | `bool` | `True` | Normalize numeric values |
| `detect_language` | `bool` | `False` | Detect document language |
-**Common Use Cases**:
-- Cleaning noisy text data
-- Standardizing date formats
-- Normalizing entity names
-- Multi-language support
-- Number format standardization
-
**API Reference**: [Normalize Module](reference/normalize.md)
+---
+
+## Core Processing Layer
+
+These modules form the intelligence of Semantica, extracting meaning, building relationships, and inferring new knowledge.
+
### 4. Semantic Extract Module
!!! abstract "Purpose"
@@ -421,13 +298,6 @@ for rel in relationships[:5]:
| `confidence_threshold`| `float` | `0.5` | Minimum confidence score |
| `custom_entity_types`| `List[str]` | `[]` | Custom entity types |
-**Common Use Cases**:
-- Named entity recognition
-- Relationship extraction
-- Semantic analysis
-- Knowledge extraction
-- Information extraction
-
**API Reference**: [Semantic Extract Module](reference/semantic_extract.md)
### 5. Knowledge Graph (KG) Module
@@ -500,15 +370,141 @@ print(f"Communities: {metrics['communities']}")
| `temporal` | `bool` | `False` | Enable temporal graph support |
| `merge_duplicates`| `bool` | `True` | Automatically merge duplicate entities|
-**Common Use Cases**:
-- Building knowledge graphs
-- Graph analytics
-- Community detection
-- Temporal analysis
-- Relationship modeling
-
**API Reference**: [Knowledge Graph Module](reference/kg.md)
+### 9. Reasoning Module
+
+!!! abstract "Purpose"
+ Goes beyond simple retrieval to infer new facts and validate existing knowledge using logical rules.
+
+**Key Features**:
+- Forward and backward chaining
+- Rule-based inference
+- Deductive and abductive reasoning
+- Explanation generation
+- RETE algorithm support
+- Custom rule definition
+
+**Input/Output Specification**:
+
+| Input | Type | Description |
+| :-------------- | :------------------ | :----------------------------------- |
+| `knowledge_graph`| `KnowledgeGraph` | Input knowledge graph |
+| `rules` | `List[Rule]` | Inference rules |
+| `method` | `str` | Reasoning method |
+
+| Output | Type | Description |
+| :------------ | :------------------ | :----------------------------------- |
+| `new_facts` | `List[Fact]` | Inferred facts |
+| `explanations`| `List[Explanation]` | Reasoning explanations |
+
+**Components**:
+- `InferenceEngine`: Main inference orchestrator
+- `RuleManager`: Manage inference rules
+- `DeductiveReasoner`: Deductive reasoning
+- `AbductiveReasoner`: Abductive reasoning
+- `ExplanationGenerator`: Generate explanations for inferences
+- `RETEEngine`: RETE algorithm for rule matching
+
+**Complete Code Example**:
+
+```python
+from semantica.reasoning import InferenceEngine, RuleManager
+
+inference_engine = InferenceEngine()
+rule_manager = RuleManager()
+
+# Define rules
+rules = [
+ "IF Person worksFor Company AND Company locatedIn City THEN Person livesIn City",
+ "IF Person hasFriend Person2 AND Person2 hasFriend Person3 THEN Person knows Person3"
+]
+
+rule_manager.add_rules(rules)
+
+# Perform inference
+new_facts = inference_engine.forward_chain(kg, rule_manager)
+print(f"Inferred {len(new_facts)} new facts")
+
+# Get explanations
+for fact in new_facts:
+ explanation = inference_engine.explain(fact)
+ print(f"{fact}: {explanation}")
+```
+
+**Configuration Options**:
+
+| Option | Type | Default | Description |
+| :-------------- | :----- | :---------------- | :--------------------------- |
+| `method` | `str` | `"forward_chain"` | Reasoning method |
+| `max_iterations`| `int` | `100` | Maximum inference iterations |
+
+**API Reference**: [Reasoning Module](reference/reasoning.md)
+
+### 10. Ontology Module
+
+!!! abstract "Purpose"
+ Defines the schema and structure of your knowledge domain, ensuring consistency and enabling interoperability.
+
+**Key Features**:
+- Automatic ontology generation (6-stage pipeline)
+- OWL/RDF export
+- Class and property inference
+- Ontology validation
+- Symbolic reasoning (HermiT, Pellet)
+- Version management
+
+**Input/Output Specification**:
+
+| Input | Type | Description |
+| :-------------- | :---------------- | :----------------------------------- |
+| `knowledge_graph`| `KnowledgeGraph` | Input knowledge graph |
+| `base_uri` | `str` | Base URI for ontology |
+
+| Output | Type | Description |
+| :---------- | :---------- | :----------------------------------- |
+| `ontology` | `Ontology` | Generated ontology |
+| `owl_content`| `str` | OWL/Turtle format |
+
+**Components**:
+- `OntologyGenerator`: Generate ontologies from knowledge graphs
+- `OntologyValidator`: Validate ontology structure
+- `OWLGenerator`: Generate OWL format ontologies
+- `PropertyGenerator`: Generate ontology properties
+- `ClassInferrer`: Infer ontology classes
+
+**Complete Code Example**:
+
+```python
+from semantica.ontology import OntologyGenerator
+
+generator = OntologyGenerator(base_uri="https://example.org/ontology/")
+ontology = generator.generate_from_graph(kg)
+
+# Validate ontology
+validator = generator.validate(ontology)
+print(f"Valid: {validator.is_valid}")
+
+# Export to OWL
+owl_content = generator.export_owl(ontology, format="turtle")
+print(f"Generated {len(owl_content)} lines of OWL")
+```
+
+**Configuration Options**:
+
+| Option | Type | Default | Description |
+| :-------- | :----- | :--------- | :--------------------------- |
+| `base_uri`| `str` | `None` | Base URI for ontology |
+| `reasoner`| `str` | `"hermit"` | Reasoner (hermit/pellet) |
+
+**API Reference**: [Ontology Module](reference/ontology.md)
+
+---
+
+## Storage & Embeddings Layer
+
+These modules handle the persistence and retrieval of data, both as vectors and as graphs.
+
### 6. Embeddings Module
!!! abstract "Purpose"
@@ -569,12 +565,6 @@ print(f"Similarity: {similarity:.3f}")
| `batch_size`| `int` | `100` | Batch size for processing |
| `cache` | `bool` | `True` | Enable caching |
-**Common Use Cases**:
-- Semantic search
-- Similarity calculation
-- RAG applications
-- Clustering and classification
-
**API Reference**: [Embeddings Module](reference/embeddings.md)
### 7. Vector Store Module
@@ -636,12 +626,6 @@ for result in results:
| `index_type` | `str` | `"flat"` | FAISS index type |
| `hybrid_search`| `bool` | `True` | Enable hybrid search |
-**Common Use Cases**:
-- Semantic search
-- Document retrieval
-- RAG applications
-- Similarity matching
-
**API Reference**: [Vector Store Module](reference/vector_store.md)
### 8. Graph Store Module
@@ -716,153 +700,13 @@ node = create_node(labels=["Entity"], properties={"name": "Test"})
| `uri` | `str` | `None` | Database connection URI |
| `database` | `str` | `"neo4j"` | Database name |
-**Common Use Cases**:
-- Persistent graph storage
-- Complex graph queries
-- Graph analytics
-- Production deployments
-- High-performance applications
-
**API Reference**: [Graph Store Module](reference/graph_store.md)
-### 9. Reasoning Module
-
-!!! abstract "Purpose"
- Goes beyond simple retrieval to infer new facts and validate existing knowledge using logical rules.
-
-**Key Features**:
-- Forward and backward chaining
-- Rule-based inference
-- Deductive and abductive reasoning
-- Explanation generation
-- RETE algorithm support
-- Custom rule definition
-
-**Input/Output Specification**:
-
-| Input | Type | Description |
-| :-------------- | :------------------ | :----------------------------------- |
-| `knowledge_graph`| `KnowledgeGraph` | Input knowledge graph |
-| `rules` | `List[Rule]` | Inference rules |
-| `method` | `str` | Reasoning method |
-
-| Output | Type | Description |
-| :------------ | :------------------ | :----------------------------------- |
-| `new_facts` | `List[Fact]` | Inferred facts |
-| `explanations`| `List[Explanation]` | Reasoning explanations |
-
-**Components**:
-- `InferenceEngine`: Main inference orchestrator
-- `RuleManager`: Manage inference rules
-- `DeductiveReasoner`: Deductive reasoning
-- `AbductiveReasoner`: Abductive reasoning
-- `ExplanationGenerator`: Generate explanations for inferences
-- `RETEEngine`: RETE algorithm for rule matching
-
-**Complete Code Example**:
-
-```python
-from semantica.reasoning import InferenceEngine, RuleManager
-
-inference_engine = InferenceEngine()
-rule_manager = RuleManager()
-
-# Define rules
-rules = [
- "IF Person worksFor Company AND Company locatedIn City THEN Person livesIn City",
- "IF Person hasFriend Person2 AND Person2 hasFriend Person3 THEN Person knows Person3"
-]
-
-rule_manager.add_rules(rules)
-
-# Perform inference
-new_facts = inference_engine.forward_chain(kg, rule_manager)
-print(f"Inferred {len(new_facts)} new facts")
-
-# Get explanations
-for fact in new_facts:
- explanation = inference_engine.explain(fact)
- print(f"{fact}: {explanation}")
-```
-
-**Configuration Options**:
-
-| Option | Type | Default | Description |
-| :-------------- | :----- | :---------------- | :--------------------------- |
-| `method` | `str` | `"forward_chain"` | Reasoning method |
-| `max_iterations`| `int` | `100` | Maximum inference iterations |
-
-**Common Use Cases**:
-- Logical inference
-- Fact discovery
-- Knowledge validation
-- Rule-based systems
-
-**API Reference**: [Reasoning Module](reference/reasoning.md)
-
-### 10. Ontology Module
-
-!!! abstract "Purpose"
- Defines the schema and structure of your knowledge domain, ensuring consistency and enabling interoperability.
-
-**Key Features**:
-- Automatic ontology generation (6-stage pipeline)
-- OWL/RDF export
-- Class and property inference
-- Ontology validation
-- Symbolic reasoning (HermiT, Pellet)
-- Version management
-
-**Input/Output Specification**:
-
-| Input | Type | Description |
-| :-------------- | :---------------- | :----------------------------------- |
-| `knowledge_graph`| `KnowledgeGraph` | Input knowledge graph |
-| `base_uri` | `str` | Base URI for ontology |
-
-| Output | Type | Description |
-| :---------- | :---------- | :----------------------------------- |
-| `ontology` | `Ontology` | Generated ontology |
-| `owl_content`| `str` | OWL/Turtle format |
-
-**Components**:
-- `OntologyGenerator`: Generate ontologies from knowledge graphs
-- `OntologyValidator`: Validate ontology structure
-- `OWLGenerator`: Generate OWL format ontologies
-- `PropertyGenerator`: Generate ontology properties
-- `ClassInferrer`: Infer ontology classes
-
-**Complete Code Example**:
-
-```python
-from semantica.ontology import OntologyGenerator
-
-generator = OntologyGenerator(base_uri="https://example.org/ontology/")
-ontology = generator.generate_from_graph(kg)
-
-# Validate ontology
-validator = generator.validate(ontology)
-print(f"Valid: {validator.is_valid}")
-
-# Export to OWL
-owl_content = generator.export_owl(ontology, format="turtle")
-print(f"Generated {len(owl_content)} lines of OWL")
-```
-
-**Configuration Options**:
-
-| Option | Type | Default | Description |
-| :-------- | :----- | :--------- | :--------------------------- |
-| `base_uri`| `str` | `None` | Base URI for ontology |
-| `reasoner`| `str` | `"hermit"` | Reasoner (hermit/pellet) |
+---
-**Common Use Cases**:
-- Schema definition
-- Data integration
-- Consistency validation
-- Semantic web applications
+## Output Layer
-**API Reference**: [Ontology Module](reference/ontology.md)
+These modules handle the export and visualization of your data.
### 11. Export Module
@@ -923,12 +767,6 @@ csv_exporter.export(kg, "output.csv")
| `include_metadata`| `bool`| `True` | Include metadata |
| `pretty_print` | `bool` | `False` | Pretty print JSON |
-**Common Use Cases**:
-- Data portability
-- Integration with other tools
-- Backup and archival
-- Data analysis
-
**API Reference**: [Export Module](reference/export.md)
### 12. Visualization Module
@@ -993,14 +831,14 @@ embed_visualizer.visualize(
| `layout` | `str` | `"force"` | Graph layout algorithm |
| `max_nodes` | `int` | `1000` | Maximum nodes to visualize |
-**Common Use Cases**:
-- Graph exploration
-- Data analysis
-- Quality assessment
-- Presentation and reporting
-
**API Reference**: [Visualization Module](reference/visualization.md)
+---
+
+## Orchestration
+
+This layer connects all other modules into a cohesive workflow.
+
### 13. Pipeline Module
!!! abstract "Purpose"
@@ -1061,12 +899,6 @@ print(f"Processed {len(result.documents)} documents")
| `max_workers` | `int` | `4` | Maximum parallel workers |
| `retry_on_failure`| `bool`| `True` | Retry failed steps |
-**Common Use Cases**:
-- End-to-end workflows
-- Performance optimization
-- Error handling
-- Batch processing
-
**API Reference**: [Pipeline Module](reference/pipeline.md)
---
diff --git a/docs/use-cases.md b/docs/use-cases.md
index 72933c26..685038c3 100644
--- a/docs/use-cases.md
+++ b/docs/use-cases.md
@@ -7,59 +7,6 @@ Semantica is designed to solve complex data challenges across various domains. T
---
-## Table of Contents
-
-- [Choosing the Right Use Case](#choosing-the-right-use-case)
-- [Use Case Comparison](#use-case-comparison)
-- [Research & Science](#research--science)
-- [Finance & Trading](#finance--trading)
-- [Healthcare & Life Sciences](#healthcare--life-sciences)
-- [Security & Intelligence](#security--intelligence)
-- [Industry & Operations](#industry--operations)
-- [Advanced AI Patterns](#advanced-ai-patterns)
-- [New Use Cases](#new-use-cases)
-
----
-
-## Choosing the Right Use Case
-
-Use this decision tree to find the use case that best fits your needs:
-
-```mermaid
-flowchart TD
- Start[What is your domain?] --> Q1{Research/Academic?}
- Q1 -->|Yes| Research[Research Paper Analysis<br/>Biomedical Knowledge Graphs]
- Q1 -->|No| Q2{Finance/Trading?}
-
- Q2 -->|Yes| Finance[Financial Market Intelligence<br/>Algorithmic Trading<br/>Blockchain Analytics]
- Q2 -->|No| Q3{Healthcare?}
-
- Q3 -->|Yes| Healthcare[Medical Record Analysis<br/>Patient Journey Mapping]
- Q3 -->|No| Q4{Security/Intelligence?}
-
- Q4 -->|Yes| Security[Cybersecurity Threat Intelligence<br/>OSINT<br/>Fraud Detection]
- Q4 -->|No| Q5{Industry/Operations?}
-
- Q5 -->|Yes| Industry[Supply Chain Optimization<br/>Renewable Energy Management]
- Q5 -->|No| Q6{AI/ML Applications?}
-
- Q6 -->|Yes| AI[GraphRAG<br/>Corporate Intelligence<br/>Legal Document Review]
- Q6 -->|No| Q7{Other?}
-
- Q7 -->|Legal| Legal[Legal Document Analysis]
- Q7 -->|Social Media| Social[Social Media Analysis]
- Q7 -->|Support| Support[Customer Support Knowledge Base]
-
- style Research fill:#e1f5fe,stroke:#01579b
- style Finance fill:#fff3e0,stroke:#ef6c00
- style Healthcare fill:#e8f5e9,stroke:#2e7d32
- style Security fill:#ffebee,stroke:#c62828
- style Industry fill:#f3e5f5,stroke:#7b1fa2
- style AI fill:#e0f2f1,stroke:#00695c
-```
-
----
-
## Use Case Comparison
| Use Case | Difficulty | Time | Domain | Key Features |
@@ -83,54 +30,37 @@ flowchart TD
- **Intermediate**: Some domain knowledge helpful
- **Advanced**: Requires domain expertise and advanced Semantica features
+---
+
## Research & Science
-### Research Paper Analysis
+<div class="grid cards" markdown>
-!!! abstract "Use Case"
+- :material-school: **Research Paper Analysis**
+ ---
Extract structured knowledge from academic papers to discover trends, relationships, and key concepts.
+
+ **Goal**: Ingest PDFs, extract entities (Authors, Concepts, Methods), and build a citation network.
+
+ **Difficulty**: Beginner | **Time**: 30 min
+
+- :material-dna: **Biomedical Knowledge Graphs**
+ ---
+ Accelerate drug discovery and understand disease pathways by connecting genes, proteins, drugs, and diseases.
+
+ **Goal**: Connect genes, proteins, drugs, and diseases from scientific literature and databases.
+
+ **Difficulty**: Intermediate | **Time**: 1-2 hours
+
+</div>
-**Difficulty**: Beginner
-**Time**: 30 minutes
-**Domain**: Research
+### Research Paper Analysis Implementation
**Prerequisites**:
- Semantica installed
-- Python 3.8+
- Sample research papers (PDF format)
-- OpenAI API key (optional, for LLM-based extraction)
-**Goal**: Ingest PDFs, extract entities (Authors, Concepts, Methods), and build a citation network.
-
-**Step-by-Step Implementation**:
-
-1. **Install and Import**
- ```python
- from semantica import Semantica
- ```
-
-2. **Initialize Semantica**
- ```python
- semantica = Semantica()
- ```
-
-3. **Build Knowledge Base**
- ```python
- result = semantica.build_knowledge_base(
- sources=["papers/paper1.pdf", "papers/paper2.pdf"],
- embeddings=True,
- graph=True
- )
- ```
-
-4. **Analyze Results**
- ```python
- kg = result["knowledge_graph"]
- print(f"Extracted {len(kg['entities'])} entities")
- print(f"Created {len(kg['relationships'])} relationships")
- ```
-
-**Complete Code Example**:
+**Code Example**:
```python
from semantica import Semantica
@@ -143,121 +73,48 @@ semantica = Semantica()
result = semantica.build_knowledge_base(
sources=[
"papers/machine_learning_survey.pdf",
- "papers/deep_learning_review.pdf",
- "papers/nlp_advances.pdf"
+ "papers/deep_learning_review.pdf"
],
embeddings=True,
graph=True,
normalize=True
)
-# Access results
-kg = result["knowledge_graph"]
-embeddings = result["embeddings"]
-
-# Filter entities by type
-authors = [e for e in kg['entities'] if e.get('type') == 'PERSON']
-concepts = [e for e in kg['entities'] if e.get('type') == 'CONCEPT']
-methods = [e for e in kg['entities'] if e.get('type') == 'METHOD']
-
-print(f"Authors: {len(authors)}")
-print(f"Concepts: {len(concepts)}")
-print(f"Methods: {len(methods)}")
-
# Visualize citation network
+kg = result["knowledge_graph"]
visualizer = KGVisualizer()
-visualizer.visualize(
- kg,
- output_format="html",
- output_path="citation_network.html"
-)
-
-# Export for analysis
-semantica.export.to_json(kg, "research_kg.json")
+visualizer.visualize(kg, output_path="citation_network.html")
```
-**Expected Output**:
-```
-Authors: 45
-Concepts: 120
-Methods: 30
-Relationships: 200
-```
-
-**Next Steps**:
-- [:material-arrow-right: View Cookbook](cookbook/use_cases/biomedical/index.ipynb)
-- [Explore Graph Analytics](reference/kg.md#graph-analytics)
-- [Learn about Visualization](reference/visualization.md)
-
----
-
-### Biomedical Knowledge Graphs
-
-!!! abstract "Use Case"
- Accelerate drug discovery and understand disease pathways by connecting genes, proteins, drugs, and diseases.
-
-**Difficulty**: Intermediate
-**Time**: 1-2 hours
-**Domain**: Healthcare/Research
+### Biomedical Knowledge Graphs Implementation
**Prerequisites**:
- Domain knowledge of biomedical concepts
- Access to biomedical literature/databases
-- LLM API access (recommended for accuracy)
-
-**Goal**: Connect genes, proteins, drugs, and diseases from scientific literature and databases.
-**Key Entities**: Gene, Protein, Drug, Disease, Pathway
-
-**Complete Code Example**:
+**Code Example**:
```python
from semantica import Semantica
from semantica.ontology import OntologyGenerator
-# Initialize with biomedical focus
semantica = Semantica()
-
-# Define custom entity types for biomedical domain
-custom_entities = ["Gene", "Protein", "Drug", "Disease", "Pathway", "Mutation"]
+custom_entities = ["Gene", "Protein", "Drug", "Disease", "Pathway"]
# Build knowledge graph
result = semantica.build_knowledge_base(
- sources=[
- "literature/cancer_research.pdf",
- "databases/gene_protein_interactions.json"
- ],
+ sources=["literature/cancer_research.pdf"],
embeddings=True,
graph=True,
custom_entity_types=custom_entities
)
-kg = result["knowledge_graph"]
-
# Generate ontology
+kg = result["knowledge_graph"]
ontology_gen = OntologyGenerator(base_uri="https://biomed.example.org/ontology/")
ontology = ontology_gen.generate_from_graph(kg)
-
-# Query disease pathways
-pathways = [r for r in kg['relationships']
- if r.get('predicate') == 'in_pathway']
-
-print(f"Found {len(pathways)} pathway relationships")
-
-# Export for further analysis
-semantica.export.to_owl(ontology, "biomedical_ontology.owl")
-```
-
-**Expected Output**:
-```
-Found 150 pathway relationships
-Generated ontology with 25 classes and 40 properties
```
-**Next Steps**:
-- [Ontology Module](reference/ontology.md)
-- [Temporal Graphs](concepts.md#5-temporal-graphs)
-
---
## Finance & Trading
@@ -338,7 +195,7 @@ Generated ontology with 25 classes and 40 properties
---
Analyze criminal networks to identify key players, communities, and suspicious patterns.
- **Goal**: Build knowledge graphs from police reports, court records, and surveillance data to detect criminal structures and relationships.
+ **Goal**: Build knowledge graphs from police reports, court records, and surveillance data.
[:material-arrow-right: View Cookbook](cookbook/use_cases/intelligence/Criminal_Network_Analysis.ipynb)
@@ -346,7 +203,7 @@ Generated ontology with 25 classes and 40 properties
---
Process forensic evidence and correlate cases using temporal knowledge graphs.
- **Goal**: Extract entities from case files, evidence logs, and witness statements to build temporal case timelines and identify cross-case connections.
+ **Goal**: Extract entities from case files to build temporal case timelines.
[:material-arrow-right: View Cookbook](cookbook/use_cases/intelligence/Law_Enforcement_Forensics.ipynb)
@@ -354,7 +211,7 @@ Generated ontology with 25 classes and 40 properties
---
Detect complex fraud rings.
- **Goal**: Build a graph of Users, Devices, IP Addresses, and Transactions to find cycles and dense subgraphs.
+ **Goal**: Build a graph of Users, Devices, IP Addresses, and Transactions to find cycles.
</div>
@@ -419,90 +276,51 @@ Generated ontology with 25 classes and 40 properties
!!! abstract "Use Case"
Analyze contracts and legal texts to extract clauses, identify relationships, and understand document structure.
-**Difficulty**: Intermediate
-**Time**: 1-2 hours
-**Domain**: Legal
+**Difficulty**: Intermediate | **Time**: 1-2 hours | **Domain**: Legal
**Prerequisites**:
- Legal document samples (contracts, agreements)
-- Understanding of legal terminology
- LLM API access (recommended)
-**Goal**: Parse contracts, extract clauses, and identify relationships like "supersedes", "amends", "references".
-
-**Complete Code Example**:
+**Code Example**:
```python
from semantica import Semantica
-from semantica.semantic_extract import NERExtractor, RelationExtractor
semantica = Semantica()
-
-# Define legal entity types
-legal_entities = [
- "Party", "Clause", "Section", "Contract", "Agreement",
- "Term", "Condition", "Obligation", "Right"
-]
+legal_entities = ["Party", "Clause", "Section", "Contract", "Term"]
# Build knowledge graph from contracts
result = semantica.build_knowledge_base(
- sources=[
- "contracts/agreement1.pdf",
- "contracts/amendment1.pdf"
- ],
+ sources=["contracts/agreement1.pdf"],
custom_entity_types=legal_entities,
graph=True,
- temporal=True # Track contract versions
+ temporal=True
)
kg = result["knowledge_graph"]
-
-# Extract clause relationships
clause_rels = [r for r in kg['relationships']
- if r.get('predicate') in ['supersedes', 'amends', 'references']]
-
+ if r.get('predicate') in ['supersedes', 'amends']]
print(f"Found {len(clause_rels)} clause relationships")
-
-# Query contract structure
-parties = [e for e in kg['entities'] if e.get('type') == 'Party']
-print(f"Parties: {[p.get('text') for p in parties]}")
-
-# Export for legal review
-semantica.export.to_json(kg, "contract_analysis.json")
-```
-
-**Expected Output**:
```
-Found 15 clause relationships
-Parties: ['Company A', 'Company B']
-```
-
----
### Social Media Analysis
!!! abstract "Use Case"
Analyze social media content to extract sentiment, trends, and relationships between users and topics.
-**Difficulty**: Beginner
-**Time**: 30 minutes
-**Domain**: Social Media
+**Difficulty**: Beginner | **Time**: 30 min | **Domain**: Social Media
**Prerequisites**:
-- Social media data (JSON, CSV, or API access)
-- Basic understanding of sentiment analysis
-
-**Goal**: Extract entities, relationships, and sentiment from social media posts to understand trends and user connections.
+- Social media data (JSON, CSV)
-**Complete Code Example**:
+**Code Example**:
```python
from semantica import Semantica
from semantica.ingest import FileIngestor
semantica = Semantica()
-
-# Ingest social media data
ingestor = FileIngestor()
posts = ingestor.ingest("social_media/posts.json")
@@ -514,52 +332,21 @@ result = semantica.build_knowledge_base(
)
kg = result["knowledge_graph"]
-
-# Analyze trends
hashtags = [e for e in kg['entities'] if e.get('text', '').startswith('#')]
-mentions = [e for e in kg['entities'] if e.get('text', '').startswith('@')]
-
print(f"Hashtags: {len(hashtags)}")
-print(f"Mentions: {len(mentions)}")
-
-# Find popular topics
-from collections import Counter
-topic_counts = Counter([e.get('text') for e in hashtags])
-print(f"Top topics: {topic_counts.most_common(10)}")
-
-# Visualize social network
-semantica.visualization.visualize_network(
- kg,
- output="social_network.html"
-)
```
-**Expected Output**:
-```
-Hashtags: 150
-Mentions: 200
-Top topics: [('AI', 45), ('MachineLearning', 30), ('Python', 25)]
-```
-
----
-
### Customer Support Knowledge Base
!!! abstract "Use Case"
Build a knowledge base from support tickets, documentation, and FAQs to improve customer service.
-**Difficulty**: Beginner
-**Time**: 30 minutes
-**Domain**: Customer Support
+**Difficulty**: Beginner | **Time**: 30 min | **Domain**: Customer Support
**Prerequisites**:
- Support tickets or documentation
-- FAQ documents
-- Basic text data
-**Goal**: Create a searchable knowledge base that connects support issues, solutions, and related topics.
-
-**Complete Code Example**:
+**Code Example**:
```python
from semantica import Semantica
@@ -567,67 +354,18 @@ from semantica.vector_store import VectorStore, HybridSearch
semantica = Semantica()
-# Build knowledge base from support docs
+# Build knowledge base
result = semantica.build_knowledge_base(
- sources=[
- "support/tickets/",
- "support/faqs/",
- "support/documentation/"
- ],
+ sources=["support/tickets/", "support/faqs/"],
embeddings=True,
graph=True
)
-kg = result["knowledge_graph"]
-embeddings = result["embeddings"]
-
-# Set up semantic search
+# Search
vector_store = VectorStore()
-vector_store.store(embeddings, result["documents"])
-
-# Search for similar issues
+vector_store.store(result["embeddings"], result["documents"])
hybrid_search = HybridSearch(vector_store)
-results = hybrid_search.search(
- query="How do I reset my password?",
- top_k=5
-)
-
-print("Similar support articles:")
-for result in results:
- print(f" - {result.document.metadata.get('title', 'N/A')} (Score: {result.score:.3f})")
-
-# Export knowledge base
-semantica.export.to_json(kg, "support_kb.json")
-```
-
-**Expected Output**:
-```
-Similar support articles:
- - Password Reset Guide (Score: 0.892)
- - Account Recovery (Score: 0.856)
- - Login Issues FAQ (Score: 0.823)
-```
-
----
-
-## Implementation Example
-
-Here is a general pattern for implementing these use cases:
-
-```python
-from semantica import Semantica
-
-# 1. Initialize with domain-specific configuration
-semantica = Semantica(domain="finance")
-
-# 2. Ingest Data
-docs = semantica.ingest.load("data/", recursive=True)
-
-# 3. Build Knowledge Graph
-kg = semantica.kg.build_graph(docs)
-
-# 4. Analyze or Query
-insights = semantica.kg.query("MATCH (c:Company)-[:HAS_RISK]->(r:Risk) RETURN c, r")
+results = hybrid_search.search(query="How do I reset my password?", top_k=5)
```
---
@@ -644,13 +382,6 @@ This guide covered use cases across multiple domains:
- **AI Applications**: GraphRAG, corporate intelligence
- **New Use Cases**: Legal analysis, social media, customer support
-Each use case follows a similar pattern:
-1. **Ingest** data from various sources
-2. **Extract** entities and relationships
-3. **Build** knowledge graph
-4. **Analyze** and query
-5. **Export** or visualize results
-
---
## Next Steps