Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

update readme

KaifAhmad1b8abe13686b2
diff --git a/LIBS_README.md b/LIBS_README.md
index cf05a8c4..caa557d0 100644
--- a/LIBS_README.md
+++ b/LIBS_README.md
@@ -79,17 +79,45 @@ pip install -e ".[dev]"
## 🎯 Quick Start
-### 1. Basic Document Processing
+> **New User-Friendly API**: Semantica now supports lazy initialization and module-level `build()` functions. No need to call `initialize()` explicitly - the framework auto-initializes on first use. You can use `semantica.build()` or access submodules via dot notation like `semantica.kg.build()`, `semantica.ingest.build()`, etc.
+
+#### API Usage Patterns
+
+**Pattern 1: Module-level build (Simplest)**
+```python
+from semantica import build
+
+# Build knowledge base - auto-initializes
+result = build(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
+```
+
+**Pattern 2: Dot notation access (Recommended for submodules)**
+```python
+import semantica
+
+# Access submodules via dot notation
+kg_result = semantica.kg.build(["doc1.pdf"], merge_entities=True)
+embeddings = semantica.embeddings.build(["text1", "text2"], data_type="text")
+ingested = semantica.ingest.build("documents/", source_type="directory")
+```
+
+**Pattern 3: Direct class usage (Advanced control)**
```python
-from semantica import Semantica
+from semantica.kg import GraphBuilder
+from semantica.embeddings import TextEmbedder
-# Initialize the framework
-semantica = Semantica()
-semantica.initialize()
+# Use classes directly for fine-grained control
+builder = GraphBuilder(merge_entities=True)
+embedder = TextEmbedder(model_name="all-MiniLM-L6-v2")
+```
-# Build knowledge base from documents
+### 1. Basic Document Processing
+```python
+from semantica import build
+
+# Build knowledge base from documents (auto-initializes)
documents = ["document1.pdf", "document2.docx", "document3.txt"]
-result = semantica.build_knowledge_base(
+result = build(
documents,
embeddings=True,
graph=True,
@@ -117,13 +145,9 @@ kg_viz.visualize_network(knowledge_graph, output="html", file_path="knowledge_gr
### 2. Web Content Processing
```python
-from semantica import Semantica
+import semantica
from semantica.ingest import WebIngestor
-# Initialize the framework
-semantica = Semantica()
-semantica.initialize()
-
# Ingest web content
web_ingestor = WebIngestor(
config={
@@ -141,23 +165,26 @@ web_content = web_ingestor.ingest_url(url)
sitemap_url = "https://example.com/sitemap.xml"
pages = web_ingestor.crawl_sitemap(sitemap_url)
-# Build knowledge base from web content
+# Build knowledge base from web content using module-level build
sources = [web_content.url for web_content in pages]
-result = semantica.build_knowledge_base(sources)
+result = semantica.build(sources)
+
+# Or use ingest module's build function
+result = semantica.ingest.build(sources)
```
### 3. Knowledge Graph Analytics
```python
-from semantica import Semantica
+import semantica
from semantica.kg import GraphBuilder, GraphAnalyzer, CentralityCalculator, CommunityDetector
-# Initialize the framework
-semantica = Semantica()
-semantica.initialize()
-
-# Build knowledge graph
+# Build knowledge graph using module-level build
sources = ["document1.pdf", "document2.pdf"]
-result = semantica.build_knowledge_base(sources, graph=True)
+result = semantica.build(sources, graph=True)
+kg_data = result["knowledge_graph"]
+
+# Or use kg module's build function directly
+result = semantica.kg.build(sources, merge_entities=True, resolve_conflicts=True)
kg_data = result["knowledge_graph"]
# Build graph object from extracted entities and relationships
@@ -252,6 +279,26 @@ print(f"Graph connectivity: {connectivity['is_connected']}")
### 1. Data Ingestion Examples
#### File Ingestion
+
+**Option 1: Using module-level build function (Recommended)**
+```python
+import semantica
+
+# Simple approach - ingest files directly
+files = semantica.ingest.build(
+ "documents/",
+ source_type="directory",
+ recursive=True,
+ extensions=[".pdf", ".docx", ".txt"]
+)
+
+for file_obj in files:
+ print(f"File: {file_obj.path}")
+ print(f"Type: {file_obj.file_type}")
+ print(f"Size: {file_obj.size} bytes")
+```
+
+**Option 2: Using FileIngestor directly (Advanced)**
```python
from semantica.ingest import FileIngestor
from pathlib import Path
@@ -391,6 +438,25 @@ results = db_ingestor.execute_query(
### 2. Semantic Extraction Examples
#### Entity Extraction
+
+**Option 1: Using module-level build function (Recommended)**
+```python
+import semantica
+
+text = "Apple Inc. is a technology company founded by Steve Jobs in Cupertino, California."
+
+# Extract entities using module-level function
+result = semantica.semantic_extract.build(text, extract_entities=True)
+entities = result.get("entities", [])
+
+for entity in entities:
+ print(f"Entity: {entity.get('text')}")
+ print(f"Type: {entity.get('type')}")
+ print(f"Confidence: {entity.get('confidence')}")
+ print()
+```
+
+**Option 2: Using NERExtractor directly (Advanced)**
```python
from semantica.semantic_extract import NERExtractor, NamedEntityRecognizer
@@ -506,6 +572,26 @@ for event in events:
### 3. Embeddings Generation Examples
#### Text Embeddings
+
+**Option 1: Using module-level build function (Recommended)**
+```python
+import semantica
+import numpy as np
+
+# Simple approach - generate embeddings directly
+texts = [
+ "First document text.",
+ "Second document text.",
+ "Third document text."
+]
+
+# Generate embeddings using module-level function
+result = semantica.embeddings.build(texts, data_type="text")
+embeddings = result["embeddings"]
+print(f"Batch embeddings shape: {embeddings.shape}")
+```
+
+**Option 2: Using TextEmbedder directly (Advanced)**
```python
import numpy as np
from semantica.embeddings import TextEmbedder, EmbeddingGenerator
@@ -586,6 +672,27 @@ print(f"Text-Image similarity: {similarity}")
### 4. Knowledge Graph Building Examples
#### Building Knowledge Graph
+
+**Option 1: Using module-level build function (Recommended)**
+```python
+import semantica
+
+# Simple approach - build knowledge graph directly from documents
+documents = ["doc1.pdf", "doc2.pdf", "doc3.txt"]
+result = semantica.kg.build(
+ documents,
+ merge_entities=True,
+ entity_resolution_strategy="fuzzy",
+ resolve_conflicts=True,
+ enable_temporal=True
+)
+
+graph = result["knowledge_graph"]
+print(f"Total entities: {len(graph.get('entities', []))}")
+print(f"Total relationships: {len(graph.get('relationships', []))}")
+```
+
+**Option 2: Using GraphBuilder directly (Advanced)**
```python
from semantica.kg import GraphBuilder, EntityResolver
from semantica.semantic_extract import NERExtractor, RelationExtractor
@@ -794,7 +901,7 @@ csv_exporter.export_knowledge_graph(graph, "knowledge_graph.csv")
### 8. Complete End-to-End Example
```python
-from semantica import Semantica
+import semantica
from semantica.ingest import FileIngestor
from semantica.semantic_extract import NERExtractor, RelationExtractor
from semantica.embeddings import EmbeddingGenerator
@@ -802,9 +909,7 @@ from semantica.kg import GraphBuilder
from semantica.kg_qa import KGQualityAssessor
from semantica.export import JSONExporter
-# Initialize framework
-semantica = Semantica()
-semantica.initialize()
+# No explicit initialization needed - framework auto-initializes on first use
# Step 1: Ingest documents
file_ingestor = FileIngestor()
@@ -1172,14 +1277,12 @@ temporal_viz.visualize_metrics_evolution(metrics_history, timestamps,
#### Quick Visualization Example
```python
-from semantica import Semantica
+import semantica
from semantica.visualization import KGVisualizer, EmbeddingVisualizer
import numpy as np
-# Initialize framework and build knowledge graph
-semantica = Semantica()
-semantica.initialize()
-result = semantica.build_knowledge_base(["document.pdf"], graph=True, embeddings=True)
+# Build knowledge graph (auto-initializes)
+result = semantica.build(["document.pdf"], graph=True, embeddings=True)
# Visualize knowledge graph
kg_viz = KGVisualizer(layout="force", color_scheme="vibrant")
@@ -1205,7 +1308,8 @@ if "embeddings" in result:
### Basic Configuration
```python
-from semantica import Semantica, Config
+import semantica
+from semantica import Config
# Create configuration
config = Config({
@@ -1223,13 +1327,14 @@ config = Config({
}
})
-# Initialize with configuration
-semantica = Semantica(config=config)
+# Use configuration with build function
+result = semantica.build(["document.pdf"], config=config)
```
### Advanced Configuration
```python
-from semantica import Semantica, Config
+import semantica
+from semantica import Config
# Advanced configuration
config = Config({
@@ -1254,8 +1359,8 @@ config = Config({
}
})
-# Initialize with advanced configuration
-semantica = Semantica(config=config)
+# Use advanced configuration with build function
+result = semantica.build(["document.pdf"], config=config)
```
## 🚀 Performance
diff --git a/semantica/__init__.py b/semantica/__init__.py
index 90532bf2..326ed6bf 100644
--- a/semantica/__init__.py
+++ b/semantica/__init__.py
@@ -8,12 +8,16 @@ Main exports:
- Semantica: Main framework class
- PipelineBuilder: Pipeline construction DSL
- Config: Configuration management
+ - build: Module-level build function for easy access
"""
__version__ = "0.1.0"
__author__ = "Semantica Contributors"
__license__ = "MIT"
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+
# Core imports
from .core import Semantica, Config, ConfigManager, LifecycleManager, PluginRegistry
@@ -57,6 +61,198 @@ from .visualization import (
TemporalVisualizer,
)
+# Import submodules for dot notation access
+import importlib
+
+# Module proxy class for submodule access
+class _ModuleProxy:
+ """Proxy class to enable dot notation access to submodules."""
+
+ def __init__(self, module_name: str):
+ self._module_name = module_name
+ self._module = None
+
+ def _get_module(self):
+ """Lazy load the module."""
+ if self._module is None:
+ self._module = importlib.import_module(f"semantica.{self._module_name}")
+ return self._module
+
+ def __getattr__(self, name: str):
+ """Delegate attribute access to the actual module."""
+ return getattr(self._get_module(), name)
+
+ def __dir__(self):
+ """Return directory of the actual module."""
+ return dir(self._get_module())
+
+# Create module proxies for submodule access
+class _SemanticaModules:
+ """Container for submodule proxies."""
+
+ def __init__(self):
+ self._kg = None
+ self._ingest = None
+ self._embeddings = None
+ self._semantic_extract = None
+ self._visualization = None
+ self._kg_qa = None
+ self._pipeline = None
+ self._parse = None
+ self._normalize = None
+ self._export = None
+ self._vector_store = None
+ self._triple_store = None
+ self._ontology = None
+
+ @property
+ def kg(self):
+ """Access knowledge graph module."""
+ if self._kg is None:
+ self._kg = _ModuleProxy("kg")
+ return self._kg
+
+ @property
+ def ingest(self):
+ """Access ingestion module."""
+ if self._ingest is None:
+ self._ingest = _ModuleProxy("ingest")
+ return self._ingest
+
+ @property
+ def embeddings(self):
+ """Access embeddings module."""
+ if self._embeddings is None:
+ self._embeddings = _ModuleProxy("embeddings")
+ return self._embeddings
+
+ @property
+ def semantic_extract(self):
+ """Access semantic extraction module."""
+ if self._semantic_extract is None:
+ self._semantic_extract = _ModuleProxy("semantic_extract")
+ return self._semantic_extract
+
+ @property
+ def visualization(self):
+ """Access visualization module."""
+ if self._visualization is None:
+ self._visualization = _ModuleProxy("visualization")
+ return self._visualization
+
+ @property
+ def kg_qa(self):
+ """Access KG quality assurance module."""
+ if self._kg_qa is None:
+ self._kg_qa = _ModuleProxy("kg_qa")
+ return self._kg_qa
+
+ @property
+ def pipeline(self):
+ """Access pipeline module."""
+ if self._pipeline is None:
+ self._pipeline = _ModuleProxy("pipeline")
+ return self._pipeline
+
+ @property
+ def parse(self):
+ """Access parsing module."""
+ if self._parse is None:
+ self._parse = _ModuleProxy("parse")
+ return self._parse
+
+ @property
+ def normalize(self):
+ """Access normalization module."""
+ if self._normalize is None:
+ self._normalize = _ModuleProxy("normalize")
+ return self._normalize
+
+ @property
+ def export(self):
+ """Access export module."""
+ if self._export is None:
+ self._export = _ModuleProxy("export")
+ return self._export
+
+ @property
+ def vector_store(self):
+ """Access vector store module."""
+ if self._vector_store is None:
+ self._vector_store = _ModuleProxy("vector_store")
+ return self._vector_store
+
+ @property
+ def triple_store(self):
+ """Access triple store module."""
+ if self._triple_store is None:
+ self._triple_store = _ModuleProxy("triple_store")
+ return self._triple_store
+
+ @property
+ def ontology(self):
+ """Access ontology module."""
+ if self._ontology is None:
+ self._ontology = _ModuleProxy("ontology")
+ return self._ontology
+
+# Create singleton instance for module access
+_modules = _SemanticaModules()
+
+# Singleton Semantica instance for module-level build()
+_semantica_instance: Optional[Semantica] = None
+
+def _get_semantica_instance(config: Optional[Union[Config, Dict[str, Any]]] = None, **kwargs) -> Semantica:
+ """Get or create singleton Semantica instance."""
+ global _semantica_instance
+ if _semantica_instance is None:
+ _semantica_instance = Semantica(config=config, **kwargs)
+ return _semantica_instance
+
+def build(
+ sources: Union[List[Union[str, Path]], str, Path],
+ config: Optional[Union[Config, Dict[str, Any]]] = None,
+ **kwargs
+) -> Dict[str, Any]:
+ """
+ Build knowledge base from data sources (module-level convenience function).
+
+ This is a user-friendly wrapper around Semantica.build_knowledge_base()
+ that handles initialization automatically.
+
+ Args:
+ sources: Data source(s) - can be a single path/URL or list of paths/URLs
+ config: Optional configuration object or dict
+ **kwargs: Additional processing options:
+ - embeddings: Whether to generate embeddings (default: True)
+ - graph: Whether to build knowledge graph (default: True)
+ - normalize: Whether to normalize data (default: True)
+ - pipeline: Custom pipeline configuration
+ - fail_fast: Whether to fail on first error (default: False)
+
+ Returns:
+ Dictionary containing:
+ - knowledge_graph: Knowledge graph data
+ - embeddings: Embedding vectors
+ - metadata: Processing metadata
+ - statistics: Processing statistics
+ - results: Processing results
+
+ Examples:
+ >>> from semantica import build
+ >>> result = build(["doc1.pdf", "doc2.docx"], embeddings=True, graph=True)
+ >>> print(result["statistics"])
+ """
+ # Normalize sources to list
+ if isinstance(sources, (str, Path)):
+ sources = [sources]
+
+ # Get or create Semantica instance
+ semantica = _get_semantica_instance(config=config, **kwargs)
+
+ # Build knowledge base (auto-initializes if needed)
+ return semantica.build_knowledge_base(sources, **kwargs)
+
__all__ = [
# Core
"Semantica",
@@ -64,6 +260,8 @@ __all__ = [
"ConfigManager",
"LifecycleManager",
"PluginRegistry",
+ # Module-level function
+ "build",
# Pipeline
"PipelineBuilder",
"ExecutionEngine",
@@ -97,3 +295,13 @@ __all__ = [
"TemporalVisualizer",
]
+# Make submodules accessible via dot notation
+# This allows: import semantica; semantica.kg.build()
+def __getattr__(name: str):
+ """Enable dot notation access to submodules."""
+ if name in ["kg", "ingest", "embeddings", "semantic_extract", "visualization",
+ "kg_qa", "pipeline", "parse", "normalize", "export",
+ "vector_store", "triple_store", "ontology"]:
+ return getattr(_modules, name)
+ raise AttributeError(f"module 'semantica' has no attribute '{name}'")
+