Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor: update embedding API in all notebooks and documentation

KaifAhmad18b6e9a1e3690
diff --git a/cookbook/advanced/03_Complete_Visualization_Suite.ipynb b/cookbook/advanced/03_Complete_Visualization_Suite.ipynb
index eb327f7a..467e5511 100644
--- a/cookbook/advanced/03_Complete_Visualization_Suite.ipynb
+++ b/cookbook/advanced/03_Complete_Visualization_Suite.ipynb
@@ -107,7 +107,7 @@
"source": [
"embedding_generator = EmbeddingGenerator()\n",
"texts = [entity.get(\"name\", \"\") for entity in entities]\n",
- "embeddings = embedding_generator.generate(texts)\n",
+ "embeddings = embedding_generator.generate_embeddings(texts, data_type=\"text\")\n",
"\n",
"labels = [entity.get(\"type\", \"Unknown\") for entity in entities]\n",
"\n",
diff --git a/cookbook/advanced/05_Multi_Format_Export.ipynb b/cookbook/advanced/05_Multi_Format_Export.ipynb
index f47055c2..edd1c196 100644
--- a/cookbook/advanced/05_Multi_Format_Export.ipynb
+++ b/cookbook/advanced/05_Multi_Format_Export.ipynb
@@ -77,7 +77,7 @@
"\n",
"embedding_generator = EmbeddingGenerator()\n",
"texts = [e[\"name\"] for e in entities]\n",
- "embeddings = embedding_generator.generate(texts)\n",
+ "embeddings = embedding_generator.generate_embeddings(texts, data_type=\"text\")\n",
"\n",
"ontology_generator = OntologyGenerator()\n",
"ontology = ontology_generator.generate_from_graph(knowledge_graph)\n"
diff --git a/cookbook/introduction/01_Welcome_to_Semantica.ipynb b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
index 2616efe8..fa61446c 100644
--- a/cookbook/introduction/01_Welcome_to_Semantica.ipynb
+++ b/cookbook/introduction/01_Welcome_to_Semantica.ipynb
@@ -27,10 +27,10 @@
"**Semantica** is a production-ready framework for:\n",
"\n",
"- **Building Knowledge Graphs**: Transform unstructured data into structured knowledge graphs\n",
- "- **Semantic Processing**: Extract entities, relationships, and meaning from text, images, and audio\n",
+ "- **Semantic Processing**: Extract entities, relationships, and meaning from text\n",
"- **GraphRAG**: Graph-based retrieval augmented generation\n",
"- **Temporal Analysis**: Time-aware knowledge graphs\n",
- "- **Multi-Modal Processing**: Handle text, images, audio, and structured data\n",
+ "- **Text Processing**: Handle text and structured data\n",
"- **Enterprise Features**: Quality assurance, conflict resolution, ontology generation\n",
"\n",
"### Use Cases\n",
@@ -201,21 +201,19 @@
"```\n",
"\n",
"### 6. EMBEDDINGS MODULE - Embedding Generation\n",
- "**Purpose**: Generate vector embeddings for various data types\n",
+ "**Purpose**: Generate vector embeddings for text data\n",
"**Components**:\n",
"- `EmbeddingGenerator`: Main embedding orchestrator\n",
"- `TextEmbedder`: Generate text embeddings\n",
- "- `ImageEmbedder`: Generate image embeddings\n",
- "- `AudioEmbedder`: Generate audio embeddings\n",
- "- `MultimodalEmbedder`: Combine multiple modalities\n",
- "- `EmbeddingOptimizer`: Optimize embedding quality\n",
- "- `ProviderAdapters`: Support for OpenAI, Cohere, etc.\n",
+ "- `VectorEmbeddingManager`: Manage embeddings for vector databases\n",
+ "- `GraphEmbeddingManager`: Manage embeddings for graph databases\n",
+ "- `ProviderAdapters`: Support for OpenAI, BGE, FastEmbed, Llama, etc.\n",
"\n",
"**Example**:\n",
"```python\n",
"from semantica.embeddings import EmbeddingGenerator\n",
"generator = EmbeddingGenerator()\n",
- "embeddings = generator.generate(documents)\n",
+ "embeddings = generator.generate_embeddings(documents, data_type=\"text\")\n",
"```\n",
"\n",
"### 7. VECTOR_STORE MODULE - Vector Database Operations\n",
diff --git a/cookbook/introduction/12_Embedding_Generation.ipynb b/cookbook/introduction/12_Embedding_Generation.ipynb
index 13438755..267af32c 100644
--- a/cookbook/introduction/12_Embedding_Generation.ipynb
+++ b/cookbook/introduction/12_Embedding_Generation.ipynb
@@ -55,10 +55,11 @@
" \"Amazon provides cloud services.\"\n",
"]\n",
"\n",
- "embeddings = generator.generate(texts)\n",
+ "embeddings = generator.generate_embeddings(texts, data_type=\"text\")\n",
"\n",
"print(f\"Generated embeddings for {len(texts)} texts\")\n",
- "print(f\"First embedding shape: {len(embeddings[0]) if embeddings else 'N/A'}\")\n"
+ "print(f\"Embeddings shape: {embeddings.shape}\")\n",
+ "print(f\"First embedding dimension: {len(embeddings[0]) if len(embeddings) > 0 else 'N/A'}\")\n"
]
},
{
diff --git a/cookbook/introduction/13_Vector_Store.ipynb b/cookbook/introduction/13_Vector_Store.ipynb
index a96e5f9d..24d14f1f 100644
--- a/cookbook/introduction/13_Vector_Store.ipynb
+++ b/cookbook/introduction/13_Vector_Store.ipynb
@@ -53,7 +53,7 @@
"generator = EmbeddingGenerator()\n",
"\n",
"texts = [\"Apple Inc.\", \"Microsoft Corporation\", \"Amazon Web Services\"]\n",
- "embeddings = generator.generate(texts)\n",
+ "embeddings = generator.generate_embeddings(texts, data_type=\"text\")\n",
"\n",
"metadata = [\n",
" {\"id\": \"1\", \"type\": \"company\"},\n",
@@ -83,7 +83,7 @@
"outputs": [],
"source": [
"query_text = \"technology company\"\n",
- "query_embedding = generator.generate([query_text])[0]\n",
+ "query_embedding = generator.generate_embeddings(query_text, data_type=\"text\")\n",
"\n",
"results = vector_store.search_vectors(query_embedding, k=3)\n",
"\n",
diff --git a/cookbook/introduction/16_Visualization.ipynb b/cookbook/introduction/16_Visualization.ipynb
index 0119900f..698152f7 100644
--- a/cookbook/introduction/16_Visualization.ipynb
+++ b/cookbook/introduction/16_Visualization.ipynb
@@ -112,7 +112,7 @@
"generator = EmbeddingGenerator()\n",
"\n",
"texts = [\"Apple Inc.\", \"Microsoft Corporation\", \"Amazon\"]\n",
- "embeddings = generator.generate(texts)\n",
+ "embeddings = generator.generate_embeddings(texts, data_type=\"text\")\n",
"labels = [\"Apple\", \"Microsoft\", \"Amazon\"]\n",
"\n",
"visualization = embedding_visualizer.visualize_2d_projection(embeddings, labels, method=\"umap\")\n"
diff --git a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
index b748c116..1bc03cfb 100644
--- a/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
+++ b/cookbook/use_cases/advanced_rag/01_GraphRAG_Complete.ipynb
@@ -761,7 +761,7 @@
"for i, chunk in enumerate(normalized_vector_chunks):\n",
" text = str(chunk.text if hasattr(chunk, 'text') else chunk)\n",
" if text.strip():\n",
- " embedding = embedding_generator.generate(text)\n",
+ " embedding = embedding_generator.generate_embeddings(text, data_type=\"text\")\n",
" vector_chunk_embeddings[f\"vector_chunk_{i}\"] = {\n",
" 'embedding': embedding,\n",
" 'text': text,\n",
@@ -777,7 +777,7 @@
"for i, chunk in enumerate(normalized_graph_chunks):\n",
" text = str(chunk.text if hasattr(chunk, 'text') else chunk)\n",
" if text.strip():\n",
- " embedding = embedding_generator.generate(text)\n",
+ " embedding = embedding_generator.generate_embeddings(text, data_type=\"text\")\n",
" graph_chunk_embeddings[f\"graph_chunk_{i}\"] = {\n",
" 'embedding': embedding,\n",
" 'text': text,\n",
@@ -815,7 +815,7 @@
" entity_text = str(entity)\n",
" \n",
" if entity_text.strip():\n",
- " embedding = embedding_generator.generate(entity_text)\n",
+ " embedding = embedding_generator.generate_embeddings(entity_text, data_type=\"text\")\n",
" entity_id = entity.get('id', entity.get('text', str(entity))) if isinstance(entity, dict) else str(entity)\n",
" entity_embeddings[entity_id] = {\n",
" 'embedding': embedding,\n",
@@ -925,7 +925,7 @@
"hybrid_search = HybridSearch(vector_store=vector_store)\n",
"\n",
"def perform_hybrid_search(query: str, top_k: int = 10):\n",
- " query_embedding = embedding_generator.generate(query)\n",
+ " query_embedding = embedding_generator.generate_embeddings(query, data_type=\"text\")\n",
" vector_results = vector_store.search(\n",
" query_vector=query_embedding,\n",
" top_k=top_k * 2\n",
diff --git a/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb b/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb
index 209c4660..88b43f61 100644
--- a/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb
+++ b/cookbook/use_cases/cybersecurity/04_Threat_Intelligence_Hybrid_RAG.ipynb
@@ -388,7 +388,7 @@
"hybrid_search = HybridSearch()\n",
"\n",
"# Generate embeddings for threat intelligence documents\n",
- "embeddings = embedding_generator.generate(all_documents)\n",
+ "embeddings = embedding_generator.generate_embeddings(all_documents, data_type=\"text\")\n",
"\n",
"# Prepare metadata for vector store\n",
"metadata = []\n",
diff --git a/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb b/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb
index b5afba61..7c5fa612 100644
--- a/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb
+++ b/cookbook/use_cases/finance/04_Investment_Analysis_Hybrid_RAG.ipynb
@@ -249,7 +249,7 @@
"vector_store = VectorStore()\n",
"hybrid_search = HybridSearch()\n",
"\n",
- "embeddings = embedding_generator.generate(all_documents)\n",
+ "embeddings = embedding_generator.generate_embeddings(all_documents, data_type=\"text\")\n",
"\n",
"metadata = []\n",
"for i, doc in enumerate(all_documents):\n",
diff --git a/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb b/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb
index 456ceba5..40e17c09 100644
--- a/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb
+++ b/cookbook/use_cases/trading/02_News_Sentiment_Analysis.ipynb
@@ -238,7 +238,7 @@
"embedding_generator = EmbeddingGenerator()\n",
"text_embedder = TextEmbedder()\n",
"\n",
- "embeddings = embedding_generator.generate(all_news_texts)\n",
+ "embeddings = embedding_generator.generate_embeddings(all_news_texts, data_type=\"text\")\n",
"\n",
"# Analyze sentiment from embeddings and article properties\n",
"sentiment_scores = []\n",
diff --git a/docs/reference/embeddings.md b/docs/reference/embeddings.md
index 8de2b32e..a04ff69a 100644
--- a/docs/reference/embeddings.md
+++ b/docs/reference/embeddings.md
@@ -1,6 +1,6 @@
# Embeddings
-> **Multi-modal embedding generation for Text, Images, and Audio.**
+> **Text embedding generation with multiple model support.**
---
@@ -12,63 +12,51 @@
---
- Sentence-transformers, OpenAI, and BGE model support
+ Sentence-transformers, OpenAI, BGE, and FastEmbed model support
-- :material-image:{ .lg .middle } **Image Embeddings**
+- :material-vector-square:{ .lg .middle } **Vector Databases**
---
- CLIP-based vision embeddings for cross-modal search
+ Specialized managers for vector database integration (FAISS, Pinecone, Qdrant, etc.)
-- :material-waveform:{ .lg .middle } **Audio Embeddings**
+- :material-graph:{ .lg .middle } **Graph Databases**
---
- MFCC, Chroma, and Spectral feature extraction via Librosa
+ Specialized managers for graph database integration (Neo4j, NetworkX, etc.)
-- :material-layers-search:{ .lg .middle } **Multimodal**
+- :material-compress:{ .lg .middle } **Pooling Strategies**
---
- Unified embedding space for searching across modalities
-
-- :material-compress:{ .lg .middle } **Optimization**
-
- ---
-
- PCA reduction, Quantization, and Pooling strategies
-
-- :material-text-short:{ .lg .middle } **Context Management**
-
- ---
-
- Sliding window chunking with sentence boundary preservation
+ Mean, Max, CLS, Attention, and Hierarchical pooling for aggregation
</div>
!!! tip "When to Use"
- **Semantic Search**: Converting text to vectors for similarity search
- - **Clustering**: Grouping similar documents or images
+ - **Clustering**: Grouping similar documents
- **Classification**: Using embeddings as features for ML models
- **RAG**: Embedding chunks for retrieval
+ - **Vector Databases**: Preparing embeddings for FAISS, Pinecone, Qdrant, etc.
+ - **Graph Databases**: Creating node and edge embeddings for Neo4j, NetworkX, etc.
---
## ⚙️ Algorithms Used
### Generation
-- **Transformer Encoding**: BERT/RoBERTa based models for text.
-- **CLIP Encoding**: Vision Transformer (ViT) for images.
-- **Feature Extraction**: Signal processing (MFCC, Spectral Contrast) for audio.
-
-### Optimization
-- **PCA**: Dimensionality reduction to reduce storage costs while preserving variance.
-- **Quantization**: Converting float32 -> int8 for 4x memory savings.
-- **Pooling**: Mean, Max, or CLS token pooling to aggregate token vectors into sentence vectors.
+- **Transformer Encoding**: BERT/RoBERTa based models for text (sentence-transformers).
+- **FastEmbed Encoding**: Fast and efficient embedding generation using FastEmbed library.
+- **Provider Adapters**: OpenAI, BGE, Llama, and FastEmbed adapters for different providers.
-### Context
-- **Sliding Window**: `[A, B, C], [B, C, D], ...` to capture context across boundaries.
-- **Sentence Splitting**: Regex-based splitting to avoid breaking sentences mid-chunk.
+### Pooling
+- **Mean Pooling**: Arithmetic mean across embedding dimension.
+- **Max Pooling**: Element-wise maximum across embedding dimension.
+- **CLS Token Pooling**: First token/embedding extraction (for transformer models).
+- **Attention-based Pooling**: Softmax-weighted sum using dot product attention scores.
+- **Hierarchical Pooling**: Two-level pooling (chunk-level then global-level mean pooling).
---
@@ -76,14 +64,17 @@
### EmbeddingGenerator
-Unified interface for all modalities.
+Unified interface for text embedding generation.
**Methods:**
| Method | Description |
|--------|-------------|
-| `generate(data, type)` | Generate embedding |
+| `generate_embeddings(data, data_type="text")` | Generate embedding |
| `process_batch(items)` | Batch generation |
+| `compare_embeddings(emb1, emb2, method="cosine")` | Calculate similarity |
+| `get_text_method()` | Get active text embedding method |
+| `get_methods_info()` | Get detailed method information |
**Example:**
@@ -91,65 +82,74 @@ Unified interface for all modalities.
from semantica.embeddings import EmbeddingGenerator
gen = EmbeddingGenerator()
-vec = gen.generate("Hello world", data_type="text")
+vec = gen.generate_embeddings("Hello world", data_type="text")
```
### TextEmbedder
-Specialized text embedding.
+Specialized text embedding generation.
**Methods:**
| Method | Description |
|--------|-------------|
-| `embed(text)` | Generate vector |
+| `embed_text(text)` | Generate vector for single text |
| `embed_batch(texts)` | Batch processing |
+| `get_method()` | Get active embedding method |
+| `get_model_info()` | Get detailed model information |
+| `get_embedding_dimension()` | Get embedding dimension |
+
+**Example:**
+
+```python
+from semantica.embeddings import TextEmbedder
-### ImageEmbedder
+embedder = TextEmbedder(method="fastembed")
+vec = embedder.embed_text("Hello world")
+```
+
+### VectorEmbeddingManager
-Specialized image embedding.
+Manages embeddings for vector databases.
**Methods:**
| Method | Description |
|--------|-------------|
-| `embed(image_path)` | Generate vector |
+| `prepare_for_vector_db(embeddings, backend, ...)` | Prepare embeddings for vector DB |
+| `batch_prepare(embeddings_list, ...)` | Batch preparation |
+| `validate_dimensions(embeddings, expected_dim)` | Validate embedding dimensions |
-### EmbeddingOptimizer
+### GraphEmbeddingManager
-Optimizes vectors.
+Manages embeddings for graph databases.
**Methods:**
| Method | Description |
|--------|-------------|
-| `reduce_dimension(vecs)` | Apply PCA |
-| `quantize(vecs)` | Apply quantization |
+| `prepare_for_graph_db(entities, relationships, ...)` | Prepare embeddings for graph DB |
+| `embed_entities(entities, ...)` | Generate entity embeddings |
+| `embed_relationships(relationships, ...)` | Generate relationship embeddings |
---
## Convenience Functions
```python
-<<<<<<< HEAD
-from semantica.embeddings import EmbeddingGenerator, embed_text, calculate_similarity
+from semantica.embeddings import embed_text, calculate_similarity, check_available_providers
# Generate embeddings
-generator = EmbeddingGenerator()
-emb1 = generator.generate_embeddings("text1", data_type="text")
-emb2 = generator.generate_embeddings("text2", data_type="text")
+emb1 = embed_text("text1", method="sentence_transformers")
+emb2 = embed_text("text2", method="fastembed")
# Similarity
score = calculate_similarity(emb1, emb2)
-=======
-from semantica.embeddings import build, embed_text, calculate_similarity
-# One-line generation
-result = build(["text1", "text2"])
-
-# Similarity
-score = calculate_similarity(vec1, vec2)
->>>>>>> origin/main
+# Check available providers
+providers = check_available_providers()
+if providers["fastembed"]:
+ print("FastEmbed is available")
```
---
@@ -170,37 +170,64 @@ export OPENAI_API_KEY=sk-...
embeddings:
text:
model: all-MiniLM-L6-v2
+ method: sentence_transformers
batch_size: 32
-
- image:
- model: clip-ViT-B-32
-
- optimization:
- quantize: false
+ normalize: true
```
---
## Integration Examples
-### Multimodal Search
+### Text Embedding with Multiple Methods
```python
-from semantica.embeddings import MultimodalEmbedder
+from semantica.embeddings import TextEmbedder, check_available_providers
from semantica.vector_store import VectorStore
-# 1. Embed Image and Text into same space
-embedder = MultimodalEmbedder()
-img_vec = embedder.embed_image("cat.jpg")
-text_vec = embedder.embed_text("A cute kitten")
+# Check available providers
+providers = check_available_providers()
+
+# Use FastEmbed if available, otherwise sentence-transformers
+if providers["fastembed"]:
+ embedder = TextEmbedder(method="fastembed", model_name="BAAI/bge-small-en-v1.5")
+else:
+ embedder = TextEmbedder(method="sentence_transformers")
+
+# Generate embeddings
+texts = ["Machine learning", "Artificial intelligence", "Deep learning"]
+embeddings = embedder.embed_batch(texts)
-# 2. Store
+# Store in vector database
store = VectorStore()
-store.store_vectors([img_vec], metadata=[{"type": "image", "path": "cat.jpg"}])
+store.store_vectors(embeddings, metadata=[{"text": t} for t in texts])
-# 3. Search with Text
-results = store.search(text_vec, k=1)
-print(f"Found: {results[0].metadata['path']}")
+# Search
+query_emb = embedder.embed_text("neural networks")
+results = store.search(query_emb, k=2)
+print(f"Found {len(results)} similar texts")
+```
+
+### Using Vector Embedding Manager
+
+```python
+from semantica.embeddings import VectorEmbeddingManager, TextEmbedder
+
+# Generate embeddings
+embedder = TextEmbedder()
+texts = ["Document 1", "Document 2", "Document 3"]
+embeddings = embedder.embed_batch(texts)
+
+# Prepare for vector database
+manager = VectorEmbeddingManager()
+formatted = manager.prepare_for_vector_db(
+ embeddings,
+ metadata=[{"id": i, "text": t} for i, t in enumerate(texts)],
+ backend="faiss"
+)
+
+# Use formatted data with your vector database
+print(f"Prepared {len(formatted['ids'])} vectors for {formatted['backend']}")
```
---
diff --git a/semantica/embeddings/__init__.py b/semantica/embeddings/__init__.py
index 43bb9c22..55ee6879 100644
--- a/semantica/embeddings/__init__.py
+++ b/semantica/embeddings/__init__.py
@@ -2,34 +2,20 @@
Embeddings Generation Module
This module provides comprehensive embedding generation and management capabilities
-for the Semantica framework, supporting text, image, audio, and multimodal content
-with multiple embedding models, optimization strategies, and similarity calculations.
+for the Semantica framework, supporting text content with multiple embedding models
+and similarity calculations.
Algorithms Used:
Embedding Generation:
- Sentence-transformers Encoding: Transformer-based sentence embedding generation using pre-trained models
- - CLIP Image Encoding: Vision transformer-based image embedding generation for cross-modal understanding
- - Librosa Audio Feature Extraction: Multi-feature audio analysis including:
- * MFCC (Mel-frequency Cepstral Coefficients): 13 coefficients for spectral representation
- * Chroma Features: 12-dimensional pitch class representation
- * Spectral Contrast: 7-dimensional spectral contrast features
- * Tonnetz: 6-dimensional tonal centroid features
- * Temporal Aggregation: Mean pooling across time frames for fixed-size vectors
+ - FastEmbed Encoding: Fast and efficient embedding generation using FastEmbed library
- Hash-based Fallback Embeddings: SHA-256 hash-based deterministic embeddings (128-dimensional)
- Batch Processing: Vectorized processing for multiple items simultaneously
- - Data Type Auto-detection: File extension-based and content-based data type detection
Similarity Calculation:
- Cosine Similarity: Dot product divided by vector norms for normalized similarity (0-1 range)
- Euclidean Similarity: L2 norm distance converted to similarity score (0-1 range)
- - Cross-modal Similarity: Pairwise cosine similarity between different modalities (text-image, image-audio, etc.)
-
-Embedding Optimization:
- - PCA (Principal Component Analysis): Variance-preserving dimension reduction using eigenvalue decomposition
- - Quantization: Bit-depth reduction (8-bit, 16-bit) for memory efficiency with dequantization
- - Dimension Truncation: Simple truncation to first N dimensions
- - Batch Normalization: L2 normalization across batch dimension for unit vectors
Pooling Strategies:
- Mean Pooling: Arithmetic mean across embedding dimension
@@ -38,64 +24,40 @@ Pooling Strategies:
- Attention-based Pooling: Softmax-weighted sum using dot product attention scores
- Hierarchical Pooling: Two-level pooling (chunk-level then global-level mean pooling)
-Multimodal Processing:
- - Dimension Alignment: Truncation/padding to align embedding dimensions across modalities
- - Concatenation: Vector concatenation for combined multimodal embeddings
- - Averaging: Mean aggregation for compact multimodal representation
- - Cross-modal Similarity: Pairwise similarity computation between different input modalities
-
-Context Management:
- - Text Splitting: Sliding window text chunking with configurable window size
- - Sentence Boundary Preservation: Regex-based sentence boundary detection (., !, ?, newline) with minimum window size constraints
- - Overlapping Windows: Sliding window with configurable overlap for context continuity
- - Context Merging: Text concatenation and metadata aggregation from multiple context windows
- - LRU-style Context Cleanup: Oldest context removal when maximum context limit reached
-
Provider Adapters:
- OpenAI API Integration: REST API-based embedding generation
- BGE Model Integration: Sentence-transformers wrapper for BAAI General Embedding models
+ - FastEmbed Integration: Fast and efficient embedding generation using FastEmbed library
- Sentence-transformers Integration: Hugging Face transformers-based embedding models
Key Features:
- - Text, image, audio, and multimodal embedding generation
+ - Text embedding generation
- Multiple embedding models and providers
- - Embedding optimization and compression
- Similarity calculation and comparison
- Pooling strategies for aggregation
- - Context window management for long texts
- Method registry for extensibility
- Configuration management with environment variables and config files
Main Classes:
- EmbeddingGenerator: Main embedding generation handler
- TextEmbedder: Text embedding generation
- - ImageEmbedder: Image embedding generation
- - AudioEmbedder: Audio embedding generation
- - MultimodalEmbedder: Multi-modal embedding support
- - EmbeddingOptimizer: Embedding optimization and fine-tuning
- - ContextManager: Embedding context management
+ - VectorEmbeddingManager: Embedding management for vector databases
+ - GraphEmbeddingManager: Embedding management for graph databases
- MethodRegistry: Registry for custom embedding methods
- EmbeddingsConfig: Configuration manager for embeddings module
Convenience Functions:
- - build: Generate embeddings from data in one call
- generate_embeddings: Generate embeddings with method dispatch
- embed_text: Text embedding wrapper
- - embed_image: Image embedding wrapper
- - embed_audio: Audio embedding wrapper
- - embed_multimodal: Multimodal embedding wrapper
- - optimize_embeddings: Embedding optimization wrapper
- calculate_similarity: Similarity calculation wrapper
- pool_embeddings: Pooling strategy wrapper
Example Usage:
- >>> from semantica.embeddings import build, embed_text, embed_image, calculate_similarity
- >>> # Using convenience function
- >>> result = build(data=["text1", "text2"], data_type="text")
+ >>> from semantica.embeddings import embed_text, calculate_similarity
>>> # Using method functions
>>> text_emb = embed_text("Hello world", method="sentence_transformers")
- >>> img_emb = embed_image("image.jpg", method="clip")
- >>> similarity = calculate_similarity(text_emb, img_emb, method="cosine")
+ >>> text_emb2 = embed_text("Hi there", method="fastembed")
+ >>> similarity = calculate_similarity(text_emb, text_emb2, method="cosine")
>>> # Using classes directly
>>> from semantica.embeddings import EmbeddingGenerator
>>> generator = EmbeddingGenerator()
@@ -110,25 +72,17 @@ from typing import Any, Dict, List, Optional, Union
import numpy as np
-from .audio_embedder import AudioEmbedder
from .config import EmbeddingsConfig, embeddings_config
-from .context_manager import ContextManager, ContextWindow
from .embedding_generator import EmbeddingGenerator
-from .embedding_optimizer import EmbeddingOptimizer
-from .image_embedder import ImageEmbedder
from .methods import (
calculate_similarity,
- embed_audio,
- embed_image,
- embed_multimodal,
+ check_available_providers,
embed_text,
generate_embeddings,
get_embedding_method,
list_available_methods,
- optimize_embeddings,
pool_embeddings,
)
-from .multimodal_embedder import MultimodalEmbedder
from .pooling_strategies import (
AttentionPooling,
CLSPooling,
@@ -138,13 +92,16 @@ from .pooling_strategies import (
PoolingStrategy,
PoolingStrategyFactory,
)
+from .graph_embedding_manager import GraphEmbeddingManager
from .provider_adapters import (
BGEAdapter,
+ FastEmbedAdapter,
LlamaAdapter,
OpenAIAdapter,
ProviderAdapter,
ProviderAdapterFactory,
)
+from .vector_embedding_manager import VectorEmbeddingManager
from .registry import MethodRegistry, method_registry
from .text_embedder import TextEmbedder
@@ -152,18 +109,16 @@ __all__ = [
# Core Classes
"EmbeddingGenerator",
"TextEmbedder",
- "ImageEmbedder",
- "AudioEmbedder",
- "MultimodalEmbedder",
- "EmbeddingOptimizer",
- "ContextManager",
- "ContextWindow",
# Provider adapters
"ProviderAdapter",
"OpenAIAdapter",
"BGEAdapter",
+ "FastEmbedAdapter",
"LlamaAdapter",
"ProviderAdapterFactory",
+ # Embedding managers
+ "VectorEmbeddingManager",
+ "GraphEmbeddingManager",
# Pooling strategies
"PoolingStrategy",
"MeanPooling",
@@ -177,100 +132,12 @@ __all__ = [
"method_registry",
"generate_embeddings",
"embed_text",
- "embed_image",
- "embed_audio",
- "embed_multimodal",
- "optimize_embeddings",
"calculate_similarity",
"pool_embeddings",
"get_embedding_method",
"list_available_methods",
+ "check_available_providers",
# Configuration
"EmbeddingsConfig",
"embeddings_config",
]
-
-def build(
- data: Union[str, Path, List[Union[str, Path]]],
- data_type: Optional[str] = None,
- model: Optional[str] = None,
- batch_size: int = 32,
- **options,
-) -> Dict[str, Any]:
- """
- Generate embeddings from data (module-level convenience function).
-
- This is a user-friendly wrapper around EmbeddingGenerator.generate_embeddings()
- that creates an EmbeddingGenerator instance and generates embeddings.
-
- Args:
- data: Input data - can be text string, file path, or list of texts/paths
- data_type: Data type - "text", "image", "audio" (auto-detected if None)
- model: Embedding model to use (default: None, uses default model)
- batch_size: Batch size for processing multiple items (default: 32)
- **options: Additional generation options
-
- Returns:
- Dictionary containing:
- - embeddings: Generated embeddings (numpy array or list of arrays)
- - metadata: Embedding metadata
- - statistics: Generation statistics
-
- Examples:
- >>> import semantica
- >>> result = semantica.embeddings.build(
- ... data=["text1", "text2", "text3"],
- ... data_type="text",
- ... model="sentence-transformers"
- ... )
- >>> print(f"Generated {len(result['embeddings'])} embeddings")
- """
- # Create EmbeddingGenerator instance
- config = {}
- if model:
- config["model"] = model
- config.update(options)
-
- generator = EmbeddingGenerator(config=config, **options)
-
- # Normalize data to list if single item
- is_single = not isinstance(data, list)
- if is_single:
- data = [data]
-
- # Generate embeddings
- if len(data) == 1:
- # Single item
- embeddings = generator.generate_embeddings(
- data[0], data_type=data_type, **options
- )
- if is_single:
- # Return single embedding array
- return {
- "embeddings": embeddings,
- "metadata": {
- "data_type": data_type or generator._detect_data_type(data[0]),
- "model": model or "default",
- "shape": embeddings.shape
- if isinstance(embeddings, np.ndarray)
- else None,
- },
- "statistics": {"total_items": 1, "successful": 1, "failed": 0},
- }
- else:
- # Batch processing
- results = generator.process_batch(data, **options)
- return {
- "embeddings": results["embeddings"],
- "metadata": {
- "data_type": data_type or "auto-detected",
- "model": model or "default",
- "batch_size": batch_size,
- },
- "statistics": {
- "total_items": results["total"],
- "successful": results["success_count"],
- "failed": results["failure_count"],
- },
- "failed_items": results.get("failed", []),
- }
diff --git a/semantica/embeddings/audio_embedder.py b/semantica/embeddings/audio_embedder.py
deleted file mode 100644
index 7491fa83..00000000
--- a/semantica/embeddings/audio_embedder.py
+++ /dev/null
@@ -1,367 +0,0 @@
-"""
-Audio Embedder Module
-
-This module provides comprehensive audio embedding generation capabilities for the
-Semantica framework, supporting librosa-based feature extraction and fallback methods.
-
-Key Features:
- - Librosa integration for audio feature extraction (MFCC, chroma, etc.)
- - Batch processing for multiple audio files
- - Fallback audio embedding methods
- - Configurable sample rate and normalization
- - Support for various audio formats
-
-Example Usage:
- >>> from semantica.embeddings import AudioEmbedder
- >>> embedder = AudioEmbedder(sample_rate=16000)
- >>> embedding = embedder.embed_audio("audio.wav")
- >>> features = embedder.extract_features("audio.wav")
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
-
-import numpy as np
-
-from ..utils.exceptions import ProcessingError, ValidationError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-
-try:
- import librosa
-
- LIBROSA_AVAILABLE = True
-except ImportError:
- LIBROSA_AVAILABLE = False
-
-
-class AudioEmbedder:
- """
- Audio embedding generator for semantic audio representation.
-
- This class provides audio embedding generation using librosa for feature
- extraction or fallback methods. Supports single audio files, batch processing,
- and detailed feature extraction.
-
- Features:
- - Librosa-based audio feature extraction (MFCC, chroma, spectral contrast)
- - Batch processing for multiple audio files
- - Fallback audio embedding methods
- - Configurable sample rate and normalization
- - Support for various audio formats (WAV, MP3, etc.)
-
- Example Usage:
- >>> embedder = AudioEmbedder(
- ... sample_rate=16000,
- ... normalize=True
- ... )
- >>> embedding = embedder.embed_audio("audio.wav")
- >>> features = embedder.extract_features("audio.wav")
- """
-
- def __init__(self, sample_rate: int = 16000, normalize: bool = True, **config):
- """
- Initialize audio embedder.
-
- Sets up the embedder with the specified audio processing configuration.
- Uses librosa for feature extraction if available, falls back to simple
- methods otherwise.
-
- Args:
- sample_rate: Target sample rate for audio processing in Hz
- (default: 16000, standard for speech)
- normalize: Whether to normalize embeddings to unit vectors (default: True)
- **config: Additional configuration options
- """
- self.logger = get_logger("audio_embedder")
- self.config = config
-
- # Audio processing configuration
- self.sample_rate = sample_rate
- self.normalize = normalize
-
- # Initialize progress tracker
- self.progress_tracker = get_progress_tracker()
-
- self.logger.debug(f"Audio embedder initialized (sample_rate: {sample_rate} Hz)")
-
- def embed_audio(self, audio_path: Union[str, Path], **options) -> np.ndarray:
- """
- Generate embedding for a single audio file.
-
- This method creates a semantic embedding vector for the input audio using
- librosa feature extraction or fallback methods. Returns a normalized vector
- suitable for similarity calculations.
-
- Args:
- audio_path: Path to audio file. Supports common formats (WAV, MP3, etc.)
- **options: Additional embedding options (currently unused)
-
- Returns:
- np.ndarray: 1D embedding vector of shape (embedding_dim,).
- Dimension is typically 38 (MFCC + chroma + contrast + tonnetz)
- or 128 for fallback method.
-
- Raises:
- ValidationError: If audio file doesn't exist
- ProcessingError: If audio cannot be processed or embedded
-
- Example:
- >>> embedder = AudioEmbedder()
- >>> embedding = embedder.embed_audio("speech.wav")
- >>> print(f"Embedding shape: {embedding.shape}")
- """
- # Track audio embedding
- tracking_id = self.progress_tracker.start_tracking(
- file=str(audio_path),
- module="embeddings",
- submodule="AudioEmbedder",
- message=f"Generating audio embedding: {audio_path}",
- )
-
- try:
- audio_path = Path(audio_path)
-
- # Validate audio file exists
- if not audio_path.exists():
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="failed",
- message=f"File not found: {audio_path}",
- )
- raise ValidationError(
- f"Audio file not found: {audio_path}. "
- "Please provide a valid audio file path."
- )
-
- if not audio_path.is_file():
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="failed",
- message=f"Path is not a file: {audio_path}",
- )
- raise ValidationError(f"Path is not a file: {audio_path}")
-
- self.logger.debug(f"Generating embedding for audio: {audio_path}")
-
- # Use librosa if available, otherwise fallback
- if LIBROSA_AVAILABLE:
- self.progress_tracker.update_tracking(
- tracking_id, message="Using librosa for feature extraction..."
- )
- result = self._embed_with_librosa(audio_path, **options)
- else:
- self.progress_tracker.update_tracking(
- tracking_id, message="Using fallback method..."
- )
- result = self._embed_fallback(audio_path, **options)
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Generated embedding (dim: {len(result)})",
- )
- return result
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise
-
- def _embed_with_librosa(self, audio_path: Path, **options) -> np.ndarray:
- """
- Embed audio using librosa feature extraction.
-
- This method extracts multiple audio features (MFCC, chroma, spectral contrast,
- tonnetz) and combines them into a single embedding vector. Features are
- aggregated by taking the mean across time frames.
-
- Features Extracted:
- - MFCC (13 coefficients): Mel-frequency cepstral coefficients
- - Chroma (12 coefficients): Chroma features
- - Spectral Contrast (7 coefficients): Spectral contrast features
- - Tonnetz (6 coefficients): Tonal centroid features
- - Total: 38-dimensional embedding
-
- Args:
- audio_path: Path to audio file
- **options: Unused (for compatibility)
-
- Returns:
- np.ndarray: Combined audio feature embedding (38 dimensions)
-
- Raises:
- ProcessingError: If audio processing or feature extraction fails
- """
- try:
- # Load audio file at specified sample rate
- y, sr = librosa.load(str(audio_path), sr=self.sample_rate)
-
- self.logger.debug(
- f"Loaded audio: duration={len(y)/sr:.2f}s, sample_rate={sr}Hz"
- )
-
- # Extract multiple audio features
- # Mel-frequency cepstral coefficients (MFCCs) - 13 coefficients
- mfccs = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=13)
-
- # Chroma features - 12 coefficients
- chroma = librosa.feature.chroma_stft(y=y, sr=sr)
-
- # Spectral contrast - 7 coefficients
- contrast = librosa.feature.spectral_contrast(y=y, sr=sr)
-
- # Tonnetz (tonal centroid) - 6 coefficients
- tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
-
- # Aggregate features by taking mean across time dimension
- # This converts time-series features to fixed-size vectors
- features = np.concatenate(
- [
- np.mean(mfccs, axis=1), # 13 dims
- np.mean(chroma, axis=1), # 12 dims
- np.mean(contrast, axis=1), # 7 dims
- np.mean(tonnetz, axis=1), # 6 dims
- ]
- ) # Total: 38 dimensions
-
- # Normalize if requested
- if self.normalize:
- norm = np.linalg.norm(features)
- if norm > 0:
- features = features / norm
-
- self.logger.debug(f"Generated librosa embedding: shape {features.shape}")
- return features.astype(np.float32)
-
- except Exception as e:
- error_msg = f"Failed to embed audio with librosa: {e}"
- self.logger.error(error_msg)
- raise ProcessingError(error_msg) from e
-
- def _embed_fallback(self, audio_path: Path, **options) -> np.ndarray:
- """Fallback audio embedding."""
- try:
- # Simple feature extraction without librosa
- # Read file size as proxy for features
- file_size = audio_path.stat().st_size
-
- # Create simple embedding from file metadata
- # (This is a placeholder - would need actual audio processing)
- embedding = np.random.rand(128).astype(np.float32)
-
- # Normalize
- if self.normalize:
- norm = np.linalg.norm(embedding)
- if norm > 0:
- embedding = embedding / norm
-
- self.logger.warning(
- "Using fallback audio embedding (librosa not available)"
- )
- return embedding
-
- except Exception as e:
- self.logger.error(f"Failed to embed audio: {e}")
- raise ProcessingError(f"Failed to embed audio: {e}")
-
- def embed_batch(self, audio_paths: List[Union[str, Path]], **options) -> np.ndarray:
- """
- Generate embeddings for multiple audio files.
-
- Args:
- audio_paths: List of audio file paths
- **options: Embedding options
-
- Returns:
- np.ndarray: Array of embeddings (n_audio, embedding_dim)
- """
- embeddings = []
-
- for audio_path in audio_paths:
- embedding = self.embed_audio(audio_path, **options)
- embeddings.append(embedding)
-
- return np.array(embeddings)
-
- def extract_features(
- self, audio_path: Union[str, Path], **options
- ) -> Dict[str, Union[np.ndarray, float]]:
- """
- Extract detailed audio features from audio file.
-
- This method extracts comprehensive audio features including MFCC, chroma,
- spectral contrast, tonnetz, tempo, and duration. Returns raw feature
- matrices (not aggregated) for detailed analysis.
-
- Args:
- audio_path: Path to audio file
- **options: Feature extraction options (currently unused)
-
- Returns:
- Dictionary containing:
- - mfcc: MFCC feature matrix (n_mfcc, n_frames)
- - chroma: Chroma feature matrix (12, n_frames)
- - spectral_contrast: Spectral contrast matrix (7, n_frames)
- - tonnetz: Tonnetz feature matrix (6, n_frames)
- - tempo: Estimated tempo in BPM (float)
- - duration: Audio duration in seconds (float)
- Returns empty dict if librosa not available or extraction fails
-
- Example:
- >>> features = embedder.extract_features("audio.wav")
- >>> print(f"Tempo: {features['tempo']} BPM")
- >>> print(f"Duration: {features['duration']}s")
- """
- audio_path = Path(audio_path)
-
- if not LIBROSA_AVAILABLE:
- self.logger.warning(
- "librosa not available for feature extraction. "
- "Install with: pip install librosa"
- )
- return {}
-
- if not audio_path.exists():
- self.logger.warning(f"Audio file not found: {audio_path}")
- return {}
-
- try:
- # Load audio
- y, sr = librosa.load(str(audio_path), sr=self.sample_rate)
-
- # Extract comprehensive features
- features = {
- "mfcc": librosa.feature.mfcc(y=y, sr=sr),
- "chroma": librosa.feature.chroma_stft(y=y, sr=sr),
- "spectral_contrast": librosa.feature.spectral_contrast(y=y, sr=sr),
- "tonnetz": librosa.feature.tonnetz(y=y, sr=sr),
- "tempo": librosa.beat.tempo(y=y, sr=sr)[0],
- "duration": len(y) / sr,
- }
-
- self.logger.debug(
- f"Extracted features from audio: "
- f"duration={features['duration']:.2f}s, tempo={features['tempo']:.1f} BPM"
- )
-
- return features
-
- except Exception as e:
- self.logger.error(f"Failed to extract audio features: {e}")
- return {}
-
- def get_embedding_dimension(self) -> int:
- """
- Get embedding dimension.
-
- Returns:
- int: Embedding dimension
- """
- # MFCC (13) + Chroma (12) + Contrast (7) + Tonnetz (6) = 38
- # But we pad/truncate to standard sizes
- return 128 # Standard dimension
diff --git a/semantica/embeddings/context_manager.py b/semantica/embeddings/context_manager.py
deleted file mode 100644
index d7babd2b..00000000
--- a/semantica/embeddings/context_manager.py
+++ /dev/null
@@ -1,397 +0,0 @@
-"""
-Context Manager Module
-
-This module provides comprehensive context window management for embedding generation
-and processing in the Semantica framework, enabling efficient handling of long texts.
-
-Key Features:
- - Context window creation and management
- - Text splitting with sentence boundary preservation
- - Context merging and retrieval
- - Configurable window size and overlap
- - Context metadata tracking
-
-Example Usage:
- >>> from semantica.embeddings import ContextManager
- >>> manager = ContextManager(window_size=512, overlap=50)
- >>> windows = manager.split_into_windows(long_text)
- >>> merged = manager.merge_contexts([window1.context_id, window2.context_id])
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from dataclasses import dataclass, field
-from typing import Any, Dict, List, Optional
-
-from ..utils.exceptions import ProcessingError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-
-
-@dataclass
-class ContextWindow:
- """
- Context window representation for text processing.
-
- This dataclass represents a window of text with its position in the original
- document and associated metadata. Used for managing text chunks in embedding
- generation and processing.
-
- Attributes:
- text: The text content of this context window
- start_index: Starting character index in original text
- end_index: Ending character index in original text
- context_id: Unique identifier for this context window
- metadata: Additional metadata dictionary (source, tags, etc.)
-
- Example:
- >>> window = ContextWindow(
- ... text="This is a context window.",
- ... start_index=0,
- ... end_index=25,
- ... context_id="uuid-123",
- ... metadata={"source": "document.txt"}
- ... )
- """
-
- text: str
- start_index: int
- end_index: int
- context_id: str
- metadata: Dict[str, Any] = field(default_factory=dict)
-
-
-class ContextManager:
- """
- Context window manager for embedding generation and text processing.
-
- This class manages context windows for processing long texts, enabling
- efficient chunking, retrieval, and merging of text contexts.
-
- Features:
- - Context window creation and storage
- - Text splitting with sentence boundary preservation
- - Context merging for combining windows
- - Configurable window size and overlap
- - Automatic context cleanup when limit reached
-
- Example Usage:
- >>> manager = ContextManager(
- ... window_size=512,
- ... overlap=50,
- ... max_contexts=100
- ... )
- >>> windows = manager.split_into_windows(long_text)
- >>> context = manager.get_context(windows[0].context_id)
- """
-
- def __init__(
- self,
- window_size: int = 512,
- overlap: int = 50,
- max_contexts: int = 100,
- **config,
- ):
- """
- Initialize context manager.
-
- Sets up the manager with specified window size, overlap, and maximum
- number of contexts to maintain in memory.
-
- Args:
- window_size: Size of context windows in characters (default: 512)
- overlap: Overlap between consecutive windows in characters (default: 50)
- max_contexts: Maximum number of contexts to keep in memory (default: 100)
- **config: Additional configuration options
- """
- self.logger = get_logger("context_manager")
- self.config = config
-
- # Window configuration
- self.window_size = window_size
- self.overlap = overlap
- self.max_contexts = max_contexts
-
- # Store contexts (context_id -> ContextWindow)
- self.contexts: Dict[str, ContextWindow] = {}
-
- # Initialize progress tracker
- self.progress_tracker = get_progress_tracker()
-
- self.logger.debug(
- f"Context manager initialized: window_size={window_size}, "
- f"overlap={overlap}, max_contexts={max_contexts}"
- )
-
- def create_context_window(
- self, text: str, start_index: int = 0, **metadata
- ) -> ContextWindow:
- """
- Create a context window from text.
-
- This method creates a new context window with a unique ID and stores it
- for later retrieval. Automatically removes oldest context if limit reached.
-
- Args:
- text: Input text content for the context window
- start_index: Starting character index in original text (default: 0)
- **metadata: Additional metadata to attach to context window
- (e.g., source, tags, document_id)
-
- Returns:
- ContextWindow: Created context window with unique ID
-
- Example:
- >>> window = manager.create_context_window(
- ... text="This is a context window.",
- ... start_index=0,
- ... source="document.txt"
- ... )
- >>> print(window.context_id)
- """
- import uuid
-
- # Generate unique context ID
- context_id = str(uuid.uuid4())
- end_index = start_index + len(text)
-
- # Create context window
- window = ContextWindow(
- text=text,
- start_index=start_index,
- end_index=end_index,
- context_id=context_id,
- metadata=metadata,
- )
-
- # Manage context storage (remove oldest if limit reached)
- if len(self.contexts) >= self.max_contexts:
- # Find and remove oldest context (by start_index)
- oldest_id = min(
- self.contexts.keys(), key=lambda k: self.contexts[k].start_index
- )
- del self.contexts[oldest_id]
- self.logger.debug(
- f"Removed oldest context {oldest_id} (limit reached: {self.max_contexts})"
- )
-
- # Store new context
- self.contexts[context_id] = window
-
- self.logger.debug(
- f"Created context window: id={context_id}, "
- f"start={start_index}, end={end_index}, "
- f"text_length={len(text)}"
- )
-
- return window
-
- def split_into_windows(
- self, text: str, preserve_sentences: bool = True, **options
- ) -> List[ContextWindow]:
- """
- Split text into context windows.
-
- This method splits long text into overlapping context windows, optionally
- preserving sentence boundaries to avoid cutting sentences in half.
-
- Splitting Strategy:
- - Creates windows of size window_size
- - Overlaps by overlap characters between windows
- - Optionally preserves sentence boundaries (default: True)
- - Ensures minimum window size (50% of window_size) when preserving sentences
-
- Args:
- text: Input text to split into windows
- preserve_sentences: Whether to preserve sentence boundaries when splitting
- (default: True). If True, windows end at sentence boundaries.
- **options: Additional options passed to create_context_window()
-
- Returns:
- List of ContextWindow: List of context windows covering the entire text
-
- Example:
- >>> long_text = "Sentence one. Sentence two! Sentence three?"
- >>> windows = manager.split_into_windows(long_text, preserve_sentences=True)
- >>> print(f"Created {len(windows)} context windows")
- """
- # Track context window splitting
- tracking_id = self.progress_tracker.start_tracking(
- file=None,
- module="embeddings",
- submodule="ContextManager",
- message=f"Splitting text into windows (length: {len(text)})",
- )
-
- try:
- if not text:
- self.logger.debug("Empty text provided, returning empty window list")
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message="Empty text, no windows created",
- )
- return []
-
- windows = []
- text_length = len(text)
- start = 0
-
- self.logger.debug(
- f"Splitting text into windows: length={text_length}, "
- f"window_size={self.window_size}, overlap={self.overlap}, "
- f"preserve_sentences={preserve_sentences}"
- )
-
- self.progress_tracker.update_tracking(
- tracking_id, message="Creating context windows..."
- )
- while start < text_length:
- # Calculate end position
- end = min(start + self.window_size, text_length)
-
- # Try to preserve sentence boundaries if requested
- if preserve_sentences and end < text_length:
- # Look for sentence boundaries (., !, ?, newline)
- for boundary in [".", "!", "?", "\n"]:
- last_boundary = text.rfind(boundary, start, end)
- # Only use boundary if it's at least 50% into the window
- # (ensures minimum window size)
- if last_boundary > start + self.window_size * 0.5:
- end = last_boundary + 1
- break
-
- # Extract window text
- window_text = text[start:end]
-
- # Create and store context window
- window = self.create_context_window(window_text, start, **options)
- windows.append(window)
-
- # Move to next window position with overlap
- start += self.window_size - self.overlap
-
- self.logger.info(f"Split text into {len(windows)} context window(s)")
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Created {len(windows)} context windows",
- )
- return windows
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise
-
- def get_context(self, context_id: str) -> Optional[ContextWindow]:
- """
- Get context window by ID.
-
- Retrieves a previously created context window using its unique identifier.
-
- Args:
- context_id: Unique context window identifier
-
- Returns:
- ContextWindow if found, None otherwise
-
- Example:
- >>> window = manager.get_context("uuid-123")
- >>> if window:
- ... print(window.text)
- """
- context = self.contexts.get(context_id)
- if context:
- self.logger.debug(f"Retrieved context: {context_id}")
- else:
- self.logger.debug(f"Context not found: {context_id}")
- return context
-
- def merge_contexts(
- self, context_ids: List[str], **options
- ) -> Optional[ContextWindow]:
- """
- Merge multiple context windows into a single window.
-
- This method combines multiple context windows by concatenating their texts
- and merging their metadata. Contexts are sorted by start_index before merging.
-
- Args:
- context_ids: List of context IDs to merge
- **options: Additional options passed to create_context_window()
-
- Returns:
- ContextWindow: Merged context window, or None if no valid contexts found.
- The merged window has:
- - Combined text from all contexts
- - Start index from first context
- - End index from last context
- - Merged metadata from all contexts
-
- Example:
- >>> merged = manager.merge_contexts(
- ... [window1.context_id, window2.context_id, window3.context_id]
- ... )
- >>> print(f"Merged text length: {len(merged.text)}")
- """
- # Retrieve all valid contexts
- contexts = [
- self.contexts.get(cid) for cid in context_ids if cid in self.contexts
- ]
- contexts = [c for c in contexts if c is not None]
-
- if not contexts:
- self.logger.warning(f"No valid contexts found for merging: {context_ids}")
- return None
-
- # Sort contexts by start index to maintain order
- contexts.sort(key=lambda c: c.start_index)
-
- # Merge texts (join with space)
- merged_text = " ".join(c.text for c in contexts)
- start_index = contexts[0].start_index
- end_index = contexts[-1].end_index
-
- # Combine metadata from all contexts
- merged_metadata = {}
- for ctx in contexts:
- merged_metadata.update(ctx.metadata)
-
- # Add merge information
- merged_metadata["merged"] = True
- merged_metadata["source_contexts"] = context_ids
- merged_metadata["num_contexts"] = len(contexts)
-
- self.logger.debug(
- f"Merged {len(contexts)} contexts: "
- f"start={start_index}, end={end_index}, "
- f"text_length={len(merged_text)}"
- )
-
- return self.create_context_window(
- merged_text, start_index, **merged_metadata, **options
- )
-
- def clear_contexts(self) -> None:
- """
- Clear all stored contexts.
-
- Removes all context windows from memory. Useful for freeing memory
- or resetting the context manager.
- """
- count = len(self.contexts)
- self.contexts.clear()
- self.logger.debug(f"Cleared {count} context(s)")
-
- def get_context_count(self) -> int:
- """
- Get number of stored contexts.
-
- Returns:
- int: Number of context windows currently stored in memory
- """
- return len(self.contexts)
diff --git a/semantica/embeddings/embedding_generator.py b/semantica/embeddings/embedding_generator.py
index 7a977a56..1f6d8e67 100644
--- a/semantica/embeddings/embedding_generator.py
+++ b/semantica/embeddings/embedding_generator.py
@@ -6,12 +6,9 @@ images, audio, and multi-modal content, with support for multiple embedding
models and optimization strategies.
Key Features:
- - Text embedding generation (multiple models: sentence-transformers, OpenAI, BGE, etc.)
+ - Text embedding generation (multiple models: sentence-transformers, OpenAI, BGE, FastEmbed, etc.)
- Image embedding generation
- - Audio embedding generation
- - Multi-modal embedding support
- Batch processing for efficiency
- - Embedding optimization and compression
- Similarity comparison utilities
Example Usage:
@@ -31,10 +28,6 @@ import numpy as np
from ..utils.exceptions import ProcessingError
from ..utils.logging import get_logger
-from .audio_embedder import AudioEmbedder
-from .embedding_optimizer import EmbeddingOptimizer
-from .image_embedder import ImageEmbedder
-from .multimodal_embedder import MultimodalEmbedder
from .text_embedder import TextEmbedder
@@ -43,14 +36,14 @@ class EmbeddingGenerator:
Main embedding generation handler.
This class provides a unified interface for generating embeddings from
- various data types (text, images, audio) using multiple embedding models.
- It handles batch processing, optimization, and similarity calculations.
+ text data using multiple embedding models.
+ It handles batch processing and similarity calculations.
Supported Models:
- sentence-transformers: High-quality sentence embeddings
- openai: OpenAI text-embedding models
- bge: BAAI General Embedding models
- - clip: CLIP for image-text embeddings
+ - fastembed: Fast and efficient text embeddings
Example Usage:
>>> generator = EmbeddingGenerator()
@@ -64,16 +57,12 @@ class EmbeddingGenerator:
"""
Initialize embedding generator.
- Sets up embedders for different data types and the embedding optimizer.
+ Sets up embedders for different data types.
Configuration can be provided via config dict or keyword arguments.
Args:
config: Configuration dictionary with keys:
- text: Text embedder configuration
- - image: Image embedder configuration
- - audio: Audio embedder configuration
- - multimodal: Multi-modal embedder configuration
- - optimizer: Embedding optimizer configuration
**kwargs: Additional configuration (merged into config)
"""
self.logger = get_logger("embedding_generator")
@@ -85,19 +74,11 @@ class EmbeddingGenerator:
# Initialize embedders for different data types
# These are lazy-loaded and only initialized when needed
text_config = self.config.get("text", {})
- image_config = self.config.get("image", {})
- audio_config = self.config.get("audio", {})
- multimodal_config = self.config.get("multimodal", {})
- optimizer_config = self.config.get("optimizer", {})
self.text_embedder = TextEmbedder(**text_config)
- self.image_embedder = ImageEmbedder(**image_config)
- self.audio_embedder = AudioEmbedder(**audio_config)
- self.multimodal_embedder = MultimodalEmbedder(**multimodal_config)
- self.embedding_optimizer = EmbeddingOptimizer(**optimizer_config)
# List of supported embedding models
- self.supported_models = ["sentence-transformers", "openai", "bge", "clip"]
+ self.supported_models = ["sentence-transformers", "openai", "bge", "fastembed"]
# Initialize progress tracker
from ..utils.progress_tracker import get_progress_tracker
@@ -106,6 +87,36 @@ class EmbeddingGenerator:
self.logger.info("Embedding generator initialized")
+ def get_text_method(self) -> str:
+ """
+ Get the active text embedding method being used.
+
+ Returns:
+ str: Active text embedding method name
+
+ Example:
+ >>> generator = EmbeddingGenerator()
+ >>> method = generator.get_text_method()
+ >>> print(f"Text method: {method}")
+ """
+ return self.text_embedder.get_method()
+
+ def get_methods_info(self) -> Dict[str, Any]:
+ """
+ Get detailed information about all active embedding methods.
+
+ Returns:
+ dict: Dictionary containing information about text embedder
+
+ Example:
+ >>> generator = EmbeddingGenerator()
+ >>> info = generator.get_methods_info()
+ >>> print(f"Text method: {info['text']['method']}")
+ """
+ return {
+ "text": self.text_embedder.get_model_info(),
+ }
+
def generate_embeddings(
self,
data: Union[str, Path, List[Union[str, Path]]],
@@ -120,11 +131,10 @@ class EmbeddingGenerator:
Args:
data: Input data to embed:
- - str: Text string or file path
- - Path: File path object
- - List: Batch of texts or file paths
- data_type: Explicit data type ("text", "image", "audio")
- If None, auto-detects from input
+ - str: Text string
+ - List: Batch of texts
+ data_type: Explicit data type ("text")
+ If None, defaults to "text"
**options: Additional generation options passed to embedder
Returns:
@@ -140,13 +150,11 @@ class EmbeddingGenerator:
>>> emb = generator.generate_embeddings("Hello world")
>>> # Batch of texts
>>> embs = generator.generate_embeddings(["text1", "text2"])
- >>> # Image file
- >>> emb = generator.generate_embeddings("image.jpg", data_type="image")
"""
- # Auto-detect data type if not provided
+ # Default to text if not provided
if data_type is None:
- data_type = self._detect_data_type(data)
- self.logger.debug(f"Auto-detected data type: {data_type}")
+ data_type = "text"
+ self.logger.debug(f"Using data type: {data_type}")
# Route to appropriate embedder based on data type
if data_type == "text":
@@ -154,93 +162,13 @@ class EmbeddingGenerator:
return self.text_embedder.embed_text(data, **options)
elif isinstance(data, list):
return self.text_embedder.embed_batch(data, **options)
- elif data_type == "image":
- if isinstance(data, (str, Path)):
- return self.image_embedder.embed_image(data, **options)
- elif isinstance(data, list):
- return self.image_embedder.embed_batch(data, **options)
- elif data_type == "audio":
- if isinstance(data, (str, Path)):
- return self.audio_embedder.embed_audio(data, **options)
- elif isinstance(data, list):
- return self.audio_embedder.embed_batch(data, **options)
else:
error_msg = (
f"Unsupported data type: {data_type}. "
- f"Supported types: text, image, audio"
+ f"Supported types: text"
)
raise ProcessingError(error_msg)
- def _detect_data_type(self, data: Union[str, Path, List]) -> str:
- """
- Detect data type from input automatically.
-
- This method analyzes the input to determine whether it's text, image,
- or audio data. For file paths, it uses file extensions. For strings,
- it defaults to text.
-
- Args:
- data: Input data to analyze
-
- Returns:
- str: Detected data type ("text", "image", or "audio")
- """
- # Handle list inputs - check first item
- if isinstance(data, list):
- if not data:
- # Empty list defaults to text
- return "text"
- # Recursively check first item
- return self._detect_data_type(data[0])
-
- # Check if input is a file path
- file_path = None
- if isinstance(data, Path):
- file_path = data
- elif isinstance(data, str):
- # Check if string is a valid file path
- potential_path = Path(data)
- if potential_path.exists():
- file_path = potential_path
-
- # If it's a file path, detect type by extension
- if file_path:
- suffix = file_path.suffix.lower()
-
- # Common image file extensions
- image_extensions = [
- ".jpg",
- ".jpeg",
- ".png",
- ".gif",
- ".bmp",
- ".tiff",
- ".webp",
- ".svg",
- ]
- # Common audio file extensions
- audio_extensions = [".mp3", ".wav", ".flac", ".aac", ".ogg", ".m4a", ".wma"]
-
- if suffix in image_extensions:
- return "image"
- elif suffix in audio_extensions:
- return "audio"
-
- # Default to text for strings or unknown file types
- return "text"
-
- def optimize_embeddings(self, embeddings: np.ndarray, **options) -> np.ndarray:
- """
- Optimize embedding quality and performance.
-
- Args:
- embeddings: Input embeddings
- **options: Optimization options
-
- Returns:
- np.ndarray: Optimized embeddings
- """
- return self.embedding_optimizer.compress(embeddings, **options)
def compare_embeddings(
self, embedding1: np.ndarray, embedding2: np.ndarray, **options
@@ -335,15 +263,3 @@ class EmbeddingGenerator:
tracking_id, status="failed", message=str(e)
)
raise
-
-
-from .embedding_optimizer import EmbeddingOptimizer as EmbeddingOptimizerImpl
-from .multimodal_embedder import MultimodalEmbedder as MultimodalEmbedderImpl
-
-# Re-export classes from other modules for convenience
-from .text_embedder import TextEmbedder as TextEmbedderImpl
-
-# Make classes available with same names
-TextEmbedder = TextEmbedderImpl
-MultiModalEmbedder = MultimodalEmbedderImpl
-EmbeddingOptimizer = EmbeddingOptimizerImpl
diff --git a/semantica/embeddings/embedding_optimizer.py b/semantica/embeddings/embedding_optimizer.py
deleted file mode 100644
index 8873cc9e..00000000
--- a/semantica/embeddings/embedding_optimizer.py
+++ /dev/null
@@ -1,417 +0,0 @@
-"""
-Embedding Optimizer Module
-
-This module provides comprehensive optimization utilities for embedding generation,
-compression, and storage in the Semantica framework.
-
-Key Features:
- - Embedding compression (PCA, quantization)
- - Dimension reduction
- - Batch processing optimization
- - Performance profiling
- - Memory optimization
-
-Example Usage:
- >>> from semantica.embeddings import EmbeddingOptimizer
- >>> optimizer = EmbeddingOptimizer(compression_method="pca", target_dimension=128)
- >>> compressed = optimizer.compress(embeddings, target_dim=64)
- >>> metrics = optimizer.profile_performance(embeddings)
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from typing import Any, Dict, List, Optional
-
-import numpy as np
-
-from ..utils.exceptions import ProcessingError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-
-try:
- from sklearn.decomposition import PCA
- from sklearn.manifold import TSNE
-
- SKLEARN_AVAILABLE = True
-except ImportError:
- SKLEARN_AVAILABLE = False
-
-
-class EmbeddingOptimizer:
- """
- Embedding optimization utilities for compression and performance.
-
- This class provides methods for compressing embeddings, reducing dimensions,
- optimizing batch processing, and profiling embedding performance.
-
- Features:
- - PCA-based dimension reduction
- - Quantization for memory efficiency
- - Batch processing optimization
- - Performance profiling and metrics
-
- Example Usage:
- >>> optimizer = EmbeddingOptimizer(
- ... compression_method="pca",
- ... target_dimension=128
- ... )
- >>> compressed = optimizer.compress(embeddings, target_dim=64)
- >>> metrics = optimizer.profile_performance(embeddings)
- """
-
- def __init__(
- self, compression_method: str = "pca", target_dimension: int = 128, **config
- ):
- """
- Initialize embedding optimizer.
-
- Sets up the optimizer with specified compression method and target dimension
- for embedding reduction operations.
-
- Args:
- compression_method: Method for compression - "pca" or "quantization"
- (default: "pca")
- target_dimension: Default target dimension for reduction (default: 128)
- **config: Additional configuration options
- """
- self.logger = get_logger("embedding_optimizer")
- self.config = config
-
- # Compression configuration
- self.compression_method = compression_method
- self.target_dimension = target_dimension
-
- # Initialize progress tracker
- self.progress_tracker = get_progress_tracker()
-
- self.logger.debug(
- f"Embedding optimizer initialized "
- f"(method: {compression_method}, target_dim: {target_dimension})"
- )
-
- def compress(
- self,
- embeddings: np.ndarray,
- target_dim: Optional[int] = None,
- method: Optional[str] = None,
- **options,
- ) -> np.ndarray:
- """
- Compress embeddings using specified method.
-
- This method reduces the size or dimension of embeddings to optimize
- storage and processing. Supports PCA-based dimension reduction and
- quantization for memory efficiency.
-
- Compression Methods:
- - "pca": Principal Component Analysis - reduces dimension while
- preserving variance (requires sklearn)
- - "quantization": Reduces precision to save memory
-
- Args:
- embeddings: Input embeddings array of shape (n_embeddings, dim)
- target_dim: Target dimension for compression (default: self.target_dimension)
- method: Compression method - "pca" or "quantization" (default: self.compression_method)
- **options: Additional compression options:
- - bits: Bit depth for quantization (default: 8)
-
- Returns:
- np.ndarray: Compressed embeddings with same or reduced dimension.
- Returns original embeddings if compression fails or not applicable.
-
- Example:
- >>> # PCA compression
- >>> compressed = optimizer.compress(embeddings, target_dim=64, method="pca")
- >>> # Quantization
- >>> quantized = optimizer.compress(embeddings, method="quantization", bits=8)
- """
- # Track embedding compression
- tracking_id = self.progress_tracker.start_tracking(
- file=None,
- module="embeddings",
- submodule="EmbeddingOptimizer",
- message=f"Compressing embeddings: {embeddings.shape}",
- )
-
- try:
- target_dim = target_dim or self.target_dimension
- method = method or self.compression_method
-
- self.logger.debug(
- f"Compressing embeddings: shape {embeddings.shape}, "
- f"method={method}, target_dim={target_dim}"
- )
-
- if method == "pca":
- self.progress_tracker.update_tracking(
- tracking_id, message="Applying PCA compression..."
- )
- result = self._compress_pca(embeddings, target_dim)
- elif method == "quantization":
- self.progress_tracker.update_tracking(
- tracking_id, message="Applying quantization..."
- )
- result = self._compress_quantization(embeddings, **options)
- else:
- self.logger.warning(
- f"Unknown compression method: {method}. Returning original embeddings."
- )
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message="Unknown method, returning original",
- )
- return embeddings
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Compressed to shape: {result.shape}",
- )
- return result
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise
-
- def _compress_pca(self, embeddings: np.ndarray, target_dim: int) -> np.ndarray:
- """
- Compress embeddings using Principal Component Analysis (PCA).
-
- PCA reduces the dimensionality of embeddings while preserving as much
- variance as possible. This is useful for reducing storage and computation
- while maintaining semantic information.
-
- Args:
- embeddings: Input embeddings array of shape (n_embeddings, dim)
- target_dim: Target dimension for reduction
-
- Returns:
- np.ndarray: Compressed embeddings of shape (n_embeddings, target_dim).
- Returns original if sklearn unavailable or target_dim >= current dim.
- """
- if not SKLEARN_AVAILABLE:
- self.logger.warning(
- "sklearn not available for PCA. Install with: pip install scikit-learn. "
- "Returning original embeddings."
- )
- return embeddings
-
- # Check if reduction is needed
- if embeddings.shape[1] <= target_dim:
- self.logger.debug(
- f"Target dimension {target_dim} >= current dimension {embeddings.shape[1]}. "
- "No reduction needed."
- )
- return embeddings
-
- try:
- # Apply PCA
- pca = PCA(n_components=target_dim)
- compressed = pca.fit_transform(embeddings)
-
- # Calculate variance preserved
- variance_ratio = np.sum(pca.explained_variance_ratio_)
- self.logger.debug(
- f"PCA compression: {embeddings.shape[1]} -> {target_dim} dims, "
- f"variance preserved: {variance_ratio:.3f}"
- )
-
- return compressed.astype(np.float32)
-
- except Exception as e:
- error_msg = f"Failed to compress with PCA: {e}"
- self.logger.error(error_msg)
- return embeddings
-
- def _compress_quantization(
- self, embeddings: np.ndarray, bits: int = 8, **options
- ) -> np.ndarray:
- """
- Compress embeddings using quantization.
-
- Quantization reduces the precision of embedding values to save memory.
- Values are quantized to specified bit depth and then dequantized back
- to float32 for use.
-
- Args:
- embeddings: Input embeddings array
- bits: Bit depth for quantization (default: 8, range: 1-16)
- **options: Unused (for compatibility)
-
- Returns:
- np.ndarray: Quantized and dequantized embeddings (same shape, reduced precision)
- """
- if bits < 1 or bits > 16:
- self.logger.warning(f"Invalid bit depth {bits}, using 8 bits")
- bits = 8
-
- # Find value range
- min_val = np.min(embeddings)
- max_val = np.max(embeddings)
-
- # Handle constant embeddings
- if max_val == min_val:
- self.logger.debug("Constant embeddings detected, returning original")
- return embeddings
-
- # Scale to [0, 2^bits - 1]
- scale = (2**bits - 1) / (max_val - min_val)
- quantized = ((embeddings - min_val) * scale).astype(np.uint8)
-
- # Dequantize back to float32
- dequantized = (quantized.astype(np.float32) / scale) + min_val
-
- self.logger.debug(
- f"Quantization: {bits} bits, "
- f"memory reduction: {embeddings.nbytes / quantized.nbytes:.2f}x"
- )
-
- return dequantized
-
- def reduce_dimensions(
- self, embeddings: np.ndarray, target_dim: int, method: str = "pca", **options
- ) -> np.ndarray:
- """
- Reduce embedding dimensions using specified method.
-
- This method reduces the dimensionality of embeddings using PCA or simple
- truncation. Useful for reducing computational requirements and storage.
-
- Reduction Methods:
- - "pca": Principal Component Analysis - preserves variance (recommended)
- - "truncate": Simple truncation - takes first target_dim dimensions
-
- Args:
- embeddings: Input embeddings array of shape (n_embeddings, dim)
- target_dim: Target dimension for reduction
- method: Reduction method - "pca" or "truncate" (default: "pca")
- **options: Additional reduction options (unused)
-
- Returns:
- np.ndarray: Reduced embeddings of shape (n_embeddings, target_dim)
-
- Example:
- >>> # PCA reduction (preserves variance)
- >>> reduced = optimizer.reduce_dimensions(embeddings, target_dim=64, method="pca")
- >>> # Truncation (simple, fast)
- >>> truncated = optimizer.reduce_dimensions(embeddings, target_dim=64, method="truncate")
- """
- self.logger.debug(
- f"Reducing dimensions: {embeddings.shape[1]} -> {target_dim} "
- f"(method: {method})"
- )
-
- if method == "pca":
- return self._compress_pca(embeddings, target_dim)
- elif method == "truncate":
- # Simple truncation: take first target_dim dimensions
- if embeddings.shape[1] <= target_dim:
- self.logger.debug("No truncation needed")
- return embeddings
- truncated = embeddings[:, :target_dim]
- self.logger.debug(
- f"Truncated embeddings: {embeddings.shape} -> {truncated.shape}"
- )
- return truncated
- else:
- self.logger.warning(
- f"Unknown reduction method: {method}. Returning original."
- )
- return embeddings
-
- def optimize_batch_processing(
- self, embeddings: List[np.ndarray], normalize: bool = True, **options
- ) -> np.ndarray:
- """
- Optimize batch processing of embeddings.
-
- This method converts a list of embeddings to a normalized batch array,
- optimizing for efficient processing and similarity calculations.
-
- Args:
- embeddings: List of embedding vectors
- normalize: Whether to normalize embeddings to unit vectors (default: True)
- **options: Additional optimization options (unused)
-
- Returns:
- np.ndarray: Optimized batch embeddings array of shape (n_embeddings, dim)
-
- Example:
- >>> embeddings_list = [emb1, emb2, emb3]
- >>> batch = optimizer.optimize_batch_processing(embeddings_list)
- >>> print(f"Batch shape: {batch.shape}") # (3, dim)
- """
- if not embeddings:
- self.logger.debug("Empty embeddings list provided")
- return np.array([])
-
- # Convert to array
- emb_array = np.array(embeddings)
-
- self.logger.debug(
- f"Optimizing batch: {len(embeddings)} embeddings, shape {emb_array.shape}"
- )
-
- # Apply normalization if requested
- if normalize:
- norms = np.linalg.norm(emb_array, axis=1, keepdims=True)
- # Avoid division by zero for zero-norm vectors
- norms[norms == 0] = 1
- emb_array = emb_array / norms
- self.logger.debug("Normalized batch embeddings")
-
- return emb_array
-
- def profile_performance(self, embeddings: np.ndarray, **options) -> Dict[str, Any]:
- """
- Profile embedding performance and characteristics.
-
- This method analyzes embeddings and returns comprehensive metrics including
- shape, memory usage, statistical properties, and sparsity.
-
- Args:
- embeddings: Input embeddings array to profile
- **options: Additional profiling options (unused)
-
- Returns:
- Dictionary containing performance metrics:
- - shape: Embedding array shape (tuple)
- - dtype: Data type (str)
- - memory_mb: Memory usage in megabytes (float)
- - mean: Mean value across all embeddings (float)
- - std: Standard deviation (float)
- - min: Minimum value (float)
- - max: Maximum value (float)
- - sparsity: Fraction of zero values (float, 0-1)
-
- Example:
- >>> metrics = optimizer.profile_performance(embeddings)
- >>> print(f"Memory: {metrics['memory_mb']:.2f} MB")
- >>> print(f"Sparsity: {metrics['sparsity']:.3f}")
- """
- metrics = {
- "shape": embeddings.shape,
- "dtype": str(embeddings.dtype),
- "memory_mb": embeddings.nbytes / (1024 * 1024),
- "mean": float(np.mean(embeddings)),
- "std": float(np.std(embeddings)),
- "min": float(np.min(embeddings)),
- "max": float(np.max(embeddings)),
- }
-
- # Calculate sparsity (fraction of zero values)
- non_zero = np.count_nonzero(embeddings)
- total = embeddings.size
- metrics["sparsity"] = 1.0 - (non_zero / total) if total > 0 else 0.0
-
- self.logger.debug(
- f"Performance profile: shape={metrics['shape']}, "
- f"memory={metrics['memory_mb']:.2f}MB, "
- f"sparsity={metrics['sparsity']:.3f}"
- )
-
- return metrics
diff --git a/semantica/embeddings/embeddings_usage.md b/semantica/embeddings/embeddings_usage.md
index ead98e05..063bc87d 100644
--- a/semantica/embeddings/embeddings_usage.md
+++ b/semantica/embeddings/embeddings_usage.md
@@ -1,43 +1,24 @@
# Embeddings Module Usage Guide
-This guide demonstrates how to use the embeddings module for generating, optimizing, and managing embeddings for text, image, audio, and multimodal content.
+This guide demonstrates how to use the embeddings module for generating and managing embeddings for text content.
## Table of Contents
1. [Basic Usage](#basic-usage)
2. [Text Embedding](#text-embedding)
-3. [Image Embedding](#image-embedding)
-4. [Audio Embedding](#audio-embedding)
-5. [Multimodal Embedding](#multimodal-embedding)
-6. [Embedding Optimization](#embedding-optimization)
-7. [Pooling Strategies](#pooling-strategies)
-8. [Similarity Calculation](#similarity-calculation)
-9. [Context Management](#context-management)
-10. [Provider Adapters](#provider-adapters)
-11. [Using Methods](#using-methods)
-12. [Using Registry](#using-registry)
-13. [Configuration](#configuration)
-14. [Advanced Examples](#advanced-examples)
+3. [Checking Embedding Methods](#checking-embedding-methods)
+4. [Pooling Strategies](#pooling-strategies)
+5. [Similarity Calculation](#similarity-calculation)
+6. [Provider Adapters](#provider-adapters)
+7. [Vector Embedding Manager](#vector-embedding-manager)
+8. [Graph Embedding Manager](#graph-embedding-manager)
+9. [Using Methods](#using-methods)
+10. [Using Registry](#using-registry)
+11. [Configuration](#configuration)
+12. [Advanced Examples](#advanced-examples)
## Basic Usage
-### Using the Convenience Function
-
-```python
-from semantica.embeddings import build
-
-# Generate embeddings from text data
-result = build(
- data=["Hello world", "How are you?", "Python programming"],
- data_type="text",
- model="sentence-transformers"
-)
-
-print(f"Generated {len(result['embeddings'])} embeddings")
-print(f"Shape: {result['embeddings'].shape}")
-print(f"Statistics: {result['statistics']}")
-```
-
### Using Main Classes
```python
@@ -101,288 +82,133 @@ for i, emb in enumerate(sentence_embeddings):
print(f"Sentence {i+1}: shape {emb.shape}")
```
-### Using Text Embedding Methods
+### FastEmbed Embedding
```python
-from semantica.embeddings.methods import embed_text
-
-# Using sentence-transformers
-emb = embed_text("Hello world", method="sentence_transformers")
-
-# Using fallback (hash-based)
-emb = embed_text("Hello world", method="fallback")
-
-# Batch processing
-texts = ["text1", "text2", "text3"]
-embs = embed_text(texts, method="sentence_transformers")
-```
-
-## Image Embedding
-
-### CLIP Image Embedding
-
-```python
-from semantica.embeddings import ImageEmbedder
+from semantica.embeddings import TextEmbedder
-# Create image embedder
-embedder = ImageEmbedder(
- model_name="ViT-B/32",
- device="cpu",
+# Create text embedder with FastEmbed
+embedder = TextEmbedder(
+ model_name="BAAI/bge-small-en-v1.5",
+ method="fastembed",
normalize=True
)
-# Single image embedding
-embedding = embedder.embed_image("photo.jpg")
-print(f"Image embedding shape: {embedding.shape}")
+# Single text embedding
+embedding = embedder.embed_text("The quick brown fox jumps over the lazy dog")
+print(f"Embedding shape: {embedding.shape}")
-# Batch image embedding
-image_paths = ["img1.jpg", "img2.png", "img3.jpeg"]
-embeddings = embedder.embed_batch(image_paths)
+# Batch text embedding (FastEmbed is optimized for batch processing)
+texts = [
+ "Python is a programming language",
+ "Machine learning is fascinating",
+ "Natural language processing"
+]
+embeddings = embedder.embed_batch(texts)
print(f"Batch embeddings shape: {embeddings.shape}") # (3, embedding_dim)
```
-### Using Image Embedding Methods
-
-```python
-from semantica.embeddings.methods import embed_image
-
-# Using CLIP
-emb = embed_image("image.jpg", method="clip")
-
-# Using fallback
-emb = embed_image("image.jpg", method="fallback")
-
-# Batch processing
-images = ["img1.jpg", "img2.png"]
-embs = embed_image(images, method="clip")
-```
-
-## Audio Embedding
-
-### Librosa Feature Extraction
+### Using Text Embedding Methods
```python
-from semantica.embeddings import AudioEmbedder
-
-# Create audio embedder
-embedder = AudioEmbedder(
- sample_rate=16000,
- normalize=True
-)
-
-# Single audio embedding
-embedding = embedder.embed_audio("speech.wav")
-print(f"Audio embedding shape: {embedding.shape}")
-
-# Extract detailed features
-features = embedder.extract_features("speech.wav")
-print(f"MFCC shape: {features['mfcc'].shape}")
-print(f"Chroma shape: {features['chroma'].shape}")
-print(f"Tempo: {features['tempo']} BPM")
-print(f"Duration: {features['duration']:.2f}s")
-```
-
-### Using Audio Embedding Methods
+from semantica.embeddings.methods import embed_text
-```python
-from semantica.embeddings.methods import embed_audio
+# Using sentence-transformers
+emb = embed_text("Hello world", method="sentence_transformers")
-# Using librosa (MFCC + chroma + spectral contrast + tonnetz)
-emb = embed_audio("audio.wav", method="librosa")
+# Using FastEmbed (fast and efficient)
+emb = embed_text("Hello world", method="fastembed")
-# Using fallback
-emb = embed_audio("audio.wav", method="fallback")
+# Using fallback (hash-based)
+emb = embed_text("Hello world", method="fallback")
# Batch processing
-audio_files = ["audio1.wav", "audio2.mp3"]
-embs = embed_audio(audio_files, method="librosa")
-```
-
-## Multimodal Embedding
-
-### Concatenation-Based Multimodal Embedding
-
-```python
-from semantica.embeddings import MultimodalEmbedder
-
-# Create multimodal embedder
-embedder = MultimodalEmbedder(
- align_modalities=True,
- normalize=True
-)
-
-# Text + Image
-embedding = embedder.embed_multimodal(
- text="A cat sitting on a mat",
- image_path="cat.jpg",
- combine_method="concat"
-)
-print(f"Multimodal embedding shape: {embedding.shape}")
-
-# All three modalities
-embedding = embedder.embed_multimodal(
- text="Speech about cats",
- image_path="cat.jpg",
- audio_path="speech.wav",
- combine_method="concat"
-)
+texts = ["text1", "text2", "text3"]
+embs = embed_text(texts, method="sentence_transformers")
+embs_fast = embed_text(texts, method="fastembed") # Faster batch processing
```
-### Averaging-Based Multimodal Embedding
-
-```python
-from semantica.embeddings import MultimodalEmbedder
-
-embedder = MultimodalEmbedder()
-
-# Mean pooling for compact representation
-embedding = embedder.embed_multimodal(
- text="A cat",
- image_path="cat.jpg",
- combine_method="mean"
-)
-print(f"Mean-pooled embedding shape: {embedding.shape}")
-```
+## Checking Embedding Methods
-### Cross-Modal Similarity
+### Checking Active Method in TextEmbedder
```python
-from semantica.embeddings import MultimodalEmbedder
+from semantica.embeddings import TextEmbedder
-embedder = MultimodalEmbedder()
+# Create embedder with specific method
+embedder = TextEmbedder(method="fastembed", model_name="BAAI/bge-small-en-v1.5")
-# Calculate text-image similarity
-similarity = embedder.compute_cross_modal_similarity(
- text="A cat sitting on a mat",
- image_path="cat.jpg"
-)
-print(f"Text-Image similarity: {similarity:.3f}")
+# Check which method is currently active
+method = embedder.get_method()
+print(f"Active method: {method}") # "fastembed", "sentence_transformers", or "fallback"
-# Calculate similarity across all modalities
-similarity = embedder.compute_cross_modal_similarity(
- text="Speech about cats",
- image_path="cat.jpg",
- audio_path="speech.wav"
-)
-print(f"Cross-modal similarity: {similarity:.3f}")
+# Get comprehensive model information
+info = embedder.get_model_info()
+print(f"Method: {info['method']}")
+print(f"Model: {info['model_name']}")
+print(f"Model loaded: {info['model_loaded']}")
+print(f"Dimension: {info['dimension']}")
+print(f"Normalize: {info['normalize']}")
+if 'device' in info:
+ print(f"Device: {info['device']}")
```
-### Using Multimodal Embedding Methods
+### Checking Methods in EmbeddingGenerator
```python
-from semantica.embeddings.methods import embed_multimodal
-
-# Concatenation
-emb = embed_multimodal(
- text="A cat",
- image_path="cat.jpg",
- method="concat"
-)
-
-# Averaging
-emb = embed_multimodal(
- text="A cat",
- image_path="cat.jpg",
- method="mean"
-)
-```
+from semantica.embeddings import EmbeddingGenerator
-## Embedding Optimization
+# Create generator
+generator = EmbeddingGenerator()
-### PCA Dimension Reduction
+# Check text embedding method
+text_method = generator.get_text_method()
+print(f"Text method: {text_method}")
-```python
-from semantica.embeddings import EmbeddingOptimizer
-
-# Create optimizer
-optimizer = EmbeddingOptimizer(
- compression_method="pca",
- target_dimension=128
-)
-
-# Compress embeddings using PCA
-embeddings = ... # Your embeddings array (n_samples, original_dim)
-compressed = optimizer.compress(
- embeddings,
- target_dim=64,
- method="pca"
-)
-print(f"Original shape: {embeddings.shape}")
-print(f"Compressed shape: {compressed.shape}")
+# Get all methods information at once
+methods_info = generator.get_methods_info()
+print(f"Text embedder: {methods_info['text']}")
```
-### Quantization
+### Checking Available Providers
```python
-from semantica.embeddings import EmbeddingOptimizer
+from semantica.embeddings import check_available_providers
-optimizer = EmbeddingOptimizer()
+# Check which embedding providers are installed and available
+providers = check_available_providers()
-# Quantize to 8-bit
-quantized = optimizer.compress(
- embeddings,
- method="quantization",
- bits=8
-)
-print(f"Memory reduction: {embeddings.nbytes / quantized.nbytes:.2f}x")
-```
-
-### Dimension Truncation
-
-```python
-from semantica.embeddings import EmbeddingOptimizer
-
-optimizer = EmbeddingOptimizer()
+print("Available providers:")
+for provider, available in providers.items():
+ status = "✓ Available" if available else "✗ Not available"
+ print(f" {provider}: {status}")
-# Simple truncation
-truncated = optimizer.reduce_dimensions(
- embeddings,
- target_dim=64,
- method="truncate"
-)
+# Use providers conditionally
+if providers["fastembed"]:
+ embedder = TextEmbedder(method="fastembed")
+ print("Using FastEmbed for embeddings")
+elif providers["sentence_transformers"]:
+ embedder = TextEmbedder(method="sentence_transformers")
+ print("Using Sentence Transformers for embeddings")
+else:
+ embedder = TextEmbedder()
+ print("Using fallback method for embeddings")
```
-### Performance Profiling
+### Listing All Available Methods
```python
-from semantica.embeddings import EmbeddingOptimizer
+from semantica.embeddings import list_available_methods
-optimizer = EmbeddingOptimizer()
-
-# Profile embedding characteristics
-metrics = optimizer.profile_performance(embeddings)
-print(f"Shape: {metrics['shape']}")
-print(f"Memory: {metrics['memory_mb']:.2f} MB")
-print(f"Mean: {metrics['mean']:.4f}")
-print(f"Std: {metrics['std']:.4f}")
-print(f"Sparsity: {metrics['sparsity']:.3f}")
-```
-
-### Using Optimization Methods
-
-```python
-from semantica.embeddings.methods import optimize_embeddings
-
-# PCA compression
-compressed = optimize_embeddings(
- embeddings,
- method="pca",
- target_dim=64
-)
-
-# Quantization
-quantized = optimize_embeddings(
- embeddings,
- method="quantization",
- bits=8
-)
+# List all available methods
+all_methods = list_available_methods()
+print("All available methods:")
+for task, methods in all_methods.items():
+ print(f" {task}: {methods}")
-# Truncation
-truncated = optimize_embeddings(
- embeddings,
- method="truncate",
- target_dim=64
-)
+# List methods for specific task
+text_methods = list_available_methods("text")
+print(f"Text embedding methods: {text_methods['text']}")
```
## Pooling Strategies
@@ -491,60 +317,6 @@ sim = calculate_similarity(emb1, emb2, method="cosine")
sim = calculate_similarity(emb1, emb2, method="euclidean")
```
-## Context Management
-
-### Text Splitting into Windows
-
-```python
-from semantica.embeddings import ContextManager
-
-# Create context manager
-manager = ContextManager(
- window_size=512,
- overlap=50,
- max_contexts=100
-)
-
-# Split long text into windows
-long_text = "..." # Your long text
-windows = manager.split_into_windows(
- long_text,
- preserve_sentences=True
-)
-
-print(f"Created {len(windows)} context windows")
-for window in windows:
- print(f"Window {window.context_id}: {window.start_index}-{window.end_index}")
-```
-
-### Context Merging
-
-```python
-from semantica.embeddings import ContextManager
-
-manager = ContextManager()
-
-# Merge multiple context windows
-merged = manager.merge_contexts(
- [window1.context_id, window2.context_id, window3.context_id]
-)
-print(f"Merged text length: {len(merged.text)}")
-```
-
-### Context Retrieval
-
-```python
-from semantica.embeddings import ContextManager
-
-manager = ContextManager()
-
-# Get context by ID
-window = manager.get_context(context_id)
-if window:
- print(f"Context text: {window.text}")
- print(f"Metadata: {window.metadata}")
-```
-
## Provider Adapters
### OpenAI Embeddings
@@ -577,6 +349,26 @@ adapter = BGEAdapter(
embedding = adapter.embed("Hello world")
```
+### FastEmbed Embeddings
+
+```python
+from semantica.embeddings import FastEmbedAdapter
+
+# Create FastEmbed adapter
+adapter = FastEmbedAdapter(
+ model_name="BAAI/bge-small-en-v1.5"
+)
+
+# Single embedding
+embedding = adapter.embed("Hello world")
+print(f"FastEmbed embedding shape: {embedding.shape}")
+
+# Batch embeddings (FastEmbed is optimized for batch processing)
+texts = ["text1", "text2", "text3"]
+embeddings = adapter.embed_batch(texts)
+print(f"Batch embeddings shape: {embeddings.shape}")
+```
+
### Provider Factory
```python
@@ -589,6 +381,260 @@ adapter = ProviderAdapterFactory.create(
)
embedding = adapter.embed("Hello world")
+
+# Create FastEmbed adapter using factory
+fastembed_adapter = ProviderAdapterFactory.create(
+ "fastembed",
+ model_name="BAAI/bge-small-en-v1.5"
+)
+embedding = fastembed_adapter.embed("Hello world")
+```
+
+## Vector Embedding Manager
+
+### Preparing Embeddings for Vector Databases
+
+```python
+from semantica.embeddings import VectorEmbeddingManager
+import numpy as np
+
+# Create vector embedding manager
+manager = VectorEmbeddingManager()
+
+# Generate embeddings (example)
+embeddings = np.random.rand(10, 384).astype(np.float32)
+metadata = [{"text": f"document_{i}", "category": "science"} for i in range(10)]
+
+# Prepare for FAISS
+formatted = manager.prepare_for_vector_db(
+ embeddings,
+ metadata=metadata,
+ backend="faiss"
+)
+
+print(f"Vectors shape: {formatted['vectors'].shape}")
+print(f"Number of vectors: {len(formatted['ids'])}")
+print(f"Backend: {formatted['backend']}")
+```
+
+### Preparing for Different Vector DB Backends
+
+```python
+from semantica.embeddings import VectorEmbeddingManager
+
+manager = VectorEmbeddingManager()
+
+# Prepare for Pinecone
+pinecone_data = manager.prepare_for_vector_db(
+ embeddings,
+ metadata=metadata,
+ backend="pinecone",
+ namespace="my_namespace"
+)
+
+# Prepare for Weaviate
+weaviate_data = manager.prepare_for_vector_db(
+ embeddings,
+ metadata=metadata,
+ backend="weaviate",
+ class_name="Document"
+)
+
+# Prepare for Qdrant
+qdrant_data = manager.prepare_for_vector_db(
+ embeddings,
+ metadata=metadata,
+ backend="qdrant"
+)
+
+# Prepare for Milvus
+milvus_data = manager.prepare_for_vector_db(
+ embeddings,
+ metadata=metadata,
+ backend="milvus"
+)
+```
+
+### Validating Embedding Dimensions
+
+```python
+from semantica.embeddings import VectorEmbeddingManager
+
+manager = VectorEmbeddingManager()
+
+# Validate dimensions for specific backend
+is_valid = manager.validate_dimensions(embeddings, backend="pinecone")
+if is_valid:
+ print("Embeddings meet Pinecone requirements")
+else:
+ print("Embeddings do not meet requirements")
+```
+
+### Normalizing Embeddings
+
+```python
+from semantica.embeddings import VectorEmbeddingManager
+
+manager = VectorEmbeddingManager()
+
+# Normalize embeddings for vector DB storage
+normalized = manager.normalize_for_storage(embeddings, method="l2")
+print(f"Normalized embeddings shape: {normalized.shape}")
+```
+
+### Batch Preparation
+
+```python
+from semantica.embeddings import VectorEmbeddingManager
+
+manager = VectorEmbeddingManager()
+
+# Prepare multiple batches
+embeddings_batch1 = np.random.rand(5, 384).astype(np.float32)
+embeddings_batch2 = np.random.rand(5, 384).astype(np.float32)
+
+batch_result = manager.batch_prepare(
+ [embeddings_batch1, embeddings_batch2],
+ backend="faiss"
+)
+
+print(f"Combined vectors shape: {batch_result['vectors'].shape}")
+print(f"Number of batches: {batch_result['num_batches']}")
+```
+
+## Graph Embedding Manager
+
+### Preparing Embeddings for Graph Databases
+
+```python
+from semantica.embeddings import GraphEmbeddingManager
+
+# Create graph embedding manager
+manager = GraphEmbeddingManager()
+
+# Define entities (nodes)
+entities = [
+ {"id": "e1", "text": "John Doe", "type": "Person"},
+ {"id": "e2", "text": "Acme Corporation", "type": "Organization"},
+ {"id": "e3", "text": "Software Engineer", "type": "Role"}
+]
+
+# Define relationships (edges)
+relationships = [
+ {"source": "e1", "target": "e2", "type": "WORKS_FOR", "text": "works at"},
+ {"source": "e1", "target": "e3", "type": "HAS_ROLE", "text": "has role"}
+]
+
+# Prepare for Neo4j
+result = manager.prepare_for_graph_db(
+ entities,
+ relationships,
+ backend="neo4j"
+)
+
+print(f"Node embeddings: {len(result['node_embeddings'])} nodes")
+print(f"Edge embeddings: {len(result['edge_embeddings'])} edges")
+print(f"Backend: {result['backend']}")
+```
+
+### Creating Node Embeddings
+
+```python
+from semantica.embeddings import GraphEmbeddingManager
+
+manager = GraphEmbeddingManager()
+
+# Create embeddings for graph nodes
+entities = [
+ {"id": "n1", "text": "Entity 1", "type": "Person"},
+ {"id": "n2", "text": "Entity 2", "type": "Organization"}
+]
+
+node_embeddings = manager.create_node_embeddings(entities, backend="neo4j")
+
+for node_id, embedding in node_embeddings.items():
+ print(f"Node {node_id}: embedding shape {embedding.shape}")
+```
+
+### Creating Edge Embeddings
+
+```python
+from semantica.embeddings import GraphEmbeddingManager
+
+manager = GraphEmbeddingManager()
+
+# Create embeddings for graph edges
+relationships = [
+ {"source": "n1", "target": "n2", "type": "RELATES_TO", "text": "related to"}
+]
+
+edge_embeddings = manager.create_edge_embeddings(relationships, backend="neo4j")
+
+for edge_id, embedding in edge_embeddings.items():
+ print(f"Edge {edge_id}: embedding shape {embedding.shape}")
+```
+
+### Embedding Entities and Relationships
+
+```python
+from semantica.embeddings import GraphEmbeddingManager
+
+manager = GraphEmbeddingManager()
+
+# Embed entities
+entities = [
+ {"id": "e1", "text": "Entity 1"},
+ {"id": "e2", "text": "Entity 2"}
+]
+entity_embeddings = manager.embed_entities(entities)
+
+# Embed relationships
+relationships = [
+ {"source": "e1", "target": "e2", "type": "CONNECTED_TO"}
+]
+relationship_embeddings = manager.embed_relationships(relationships)
+```
+
+### Integration with Different Graph DB Backends
+
+```python
+from semantica.embeddings import GraphEmbeddingManager
+
+manager = GraphEmbeddingManager()
+
+entities = [
+ {"id": "n1", "text": "Node 1"},
+ {"id": "n2", "text": "Node 2"}
+]
+
+# Prepare for Neo4j
+neo4j_result = manager.prepare_for_graph_db(
+ entities,
+ backend="neo4j",
+ database="my_database",
+ label="Node"
+)
+
+# Prepare for NetworkX
+networkx_result = manager.prepare_for_graph_db(
+ entities,
+ backend="networkx",
+ graph_type="DiGraph"
+)
+
+# Prepare for KuzuDB
+kuzu_result = manager.prepare_for_graph_db(
+ entities,
+ backend="kuzu",
+ database_path="./kuzu_db"
+)
+
+# Prepare for FalkorDB
+falkordb_result = manager.prepare_for_graph_db(
+ entities,
+ backend="falkordb",
+ graph_name="my_graph"
+)
```
## Using Methods
@@ -714,7 +760,6 @@ embeddings:
dimension: 384
normalize: true
device: "cpu"
- compression_method: "pca"
window_size: 512
overlap: 50
@@ -727,9 +772,6 @@ embeddings_methods:
model_name: "ViT-B/32"
device: "cpu"
normalize: true
- audio:
- sample_rate: 16000
- normalize: true
```
```python
@@ -746,7 +788,6 @@ config = EmbeddingsConfig(config_file="config.yaml")
```python
from semantica.embeddings import (
EmbeddingGenerator,
- EmbeddingOptimizer,
calculate_similarity
)
@@ -755,30 +796,26 @@ generator = EmbeddingGenerator()
texts = ["text1", "text2", "text3"]
embeddings = generator.generate_embeddings(texts, data_type="text")
-# Step 2: Optimize embeddings
-optimizer = EmbeddingOptimizer()
-compressed = optimizer.compress(embeddings, target_dim=64, method="pca")
-
-# Step 3: Calculate similarities
-similarity = calculate_similarity(compressed[0], compressed[1], method="cosine")
+# Step 2: Calculate similarities
+similarity = calculate_similarity(embeddings[0], embeddings[1], method="cosine")
print(f"Similarity: {similarity:.3f}")
```
-### Multimodal Search
+### Text-Image Search
```python
-from semantica.embeddings import MultimodalEmbedder, calculate_similarity
+from semantica.embeddings import EmbeddingGenerator, calculate_similarity
-embedder = MultimodalEmbedder()
+generator = EmbeddingGenerator()
# Embed query (text)
-query_emb = embedder.embed_text("A cat sitting on a mat")
+query_emb = generator.generate_embeddings("A cat sitting on a mat", data_type="text")
# Embed documents (images)
doc_embs = [
- embedder.embed_image("cat1.jpg"),
- embedder.embed_image("dog1.jpg"),
- embedder.embed_image("cat2.jpg"),
+ generator.generate_embeddings("cat1.jpg", data_type="image"),
+ generator.generate_embeddings("dog1.jpg", data_type="image"),
+ generator.generate_embeddings("cat2.jpg", data_type="image"),
]
# Find most similar
@@ -852,27 +889,17 @@ embedding = embed_text("Hello world", method="tfidf")
embeddings = embedder.embed_batch(texts) # Faster than loop
```
-3. **Dimension Optimization**: Use PCA for dimension reduction when storage is a concern
- ```python
- compressed = optimizer.compress(embeddings, target_dim=64, method="pca")
- ```
-
-4. **Context Windows**: Use context windows for long texts to maintain semantic coherence
+3. **Context Windows**: Use context windows for long texts to maintain semantic coherence
```python
windows = manager.split_into_windows(long_text, preserve_sentences=True)
```
-5. **Cross-Modal Similarity**: Use cross-modal similarity for multimodal search and retrieval
- ```python
- similarity = embedder.compute_cross_modal_similarity(text="A cat", image_path="cat.jpg")
- ```
-
-6. **Configuration Management**: Use environment variables or config files for consistent settings
+4. **Configuration Management**: Use environment variables or config files for consistent settings
```python
embeddings_config.set("model", "all-MiniLM-L6-v2")
```
-7. **Error Handling**: Always handle fallback methods when dependencies are unavailable
+5. **Error Handling**: Always handle fallback methods when dependencies are unavailable
```python
try:
emb = embed_text(text, method="sentence_transformers")
@@ -892,17 +919,12 @@ embedding = embed_text("Hello world", method="tfidf")
embeddings_config.set("batch_size", 64) # Larger for more memory
```
-3. **Quantization**: Use quantization for memory-constrained environments
- ```python
- quantized = optimize_embeddings(embeddings, method="quantization", bits=8)
- ```
-
-4. **Caching**: Cache embeddings for repeated queries
+3. **Caching**: Cache embeddings for repeated queries
```python
# Store embeddings in cache/database for reuse
```
-5. **Parallel Processing**: Process multiple files in parallel when possible
+4. **Parallel Processing**: Process multiple files in parallel when possible
```python
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as executor:
diff --git a/semantica/embeddings/graph_embedding_manager.py b/semantica/embeddings/graph_embedding_manager.py
new file mode 100644
index 00000000..27808e8e
--- /dev/null
+++ b/semantica/embeddings/graph_embedding_manager.py
@@ -0,0 +1,405 @@
+"""
+Graph Embedding Manager Module
+
+This module provides utilities for managing embeddings specifically for graph databases,
+including entity embedding, relationship embedding, and integration helpers for various
+graph DB backends.
+
+Key Features:
+ - Generate embeddings for graph entities (nodes)
+ - Generate embeddings for graph relationships (edges)
+ - Format embeddings for graph DB storage
+ - Integration helpers for Neo4j, NetworkX, KuzuDB, FalkorDB
+
+Example Usage:
+ >>> from semantica.embeddings import GraphEmbeddingManager
+ >>> manager = GraphEmbeddingManager()
+ >>> node_embeddings = manager.create_node_embeddings(entities, backend="neo4j")
+"""
+
+from typing import Any, Dict, List, Optional, Union
+
+import numpy as np
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .embedding_generator import EmbeddingGenerator
+
+
+class GraphEmbeddingManager:
+ """
+ Manager for embeddings in graph database contexts.
+
+ This class provides utilities for generating and managing embeddings
+ specifically for graph database storage, including node and edge embeddings.
+ Supports multiple graph DB backends with backend-specific optimizations.
+
+ Supported Backends:
+ - Neo4j: Graph database with Cypher query language
+ - NetworkX: Python graph library
+ - KuzuDB: Embedded graph database
+ - FalkorDB: Redis-based graph database
+
+ Example Usage:
+ >>> manager = GraphEmbeddingManager()
+ >>> # Create node embeddings
+ >>> node_embeddings = manager.create_node_embeddings(
+ ... entities,
+ ... backend="neo4j"
+ ... )
+ >>> # Create edge embeddings
+ >>> edge_embeddings = manager.create_edge_embeddings(
+ ... relationships,
+ ... backend="neo4j"
+ ... )
+ """
+
+ def __init__(self, embedding_generator: Optional[EmbeddingGenerator] = None):
+ """
+ Initialize graph embedding manager.
+
+ Args:
+ embedding_generator: Optional EmbeddingGenerator instance for
+ generating embeddings if needed
+ """
+ self.logger = get_logger("graph_embedding_manager")
+ self.embedding_generator = embedding_generator or EmbeddingGenerator()
+
+ def prepare_for_graph_db(
+ self,
+ entities: List[Dict[str, Any]],
+ relationships: Optional[List[Dict[str, Any]]] = None,
+ backend: str = "neo4j",
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Prepare embeddings for graph database storage.
+
+ Generates and formats embeddings for both entities (nodes) and relationships (edges)
+ according to backend-specific requirements.
+
+ Args:
+ entities: List of entity dictionaries with at least "id" and "text" or "content"
+ relationships: Optional list of relationship dictionaries with
+ "source", "target", and optionally "text" or "type"
+ backend: Graph DB backend ("neo4j", "networkx", "kuzu", "falkordb")
+ **options: Additional backend-specific options
+
+ Returns:
+ Dictionary containing:
+ - node_embeddings: Dictionary mapping node IDs to embeddings
+ - edge_embeddings: Dictionary mapping edge IDs to embeddings (if provided)
+ - nodes: Formatted node data with embeddings
+ - edges: Formatted edge data with embeddings (if provided)
+ - backend_info: Backend-specific information
+
+ Raises:
+ ProcessingError: If entities are invalid or backend is unsupported
+
+ Example:
+ >>> entities = [
+ ... {"id": "e1", "text": "Entity 1", "type": "Person"},
+ ... {"id": "e2", "text": "Entity 2", "type": "Organization"}
+ ... ]
+ >>> relationships = [
+ ... {"source": "e1", "target": "e2", "type": "WORKS_FOR"}
+ ... ]
+ >>> result = manager.prepare_for_graph_db(
+ ... entities, relationships, backend="neo4j"
+ ... )
+ """
+ if backend.lower() not in ["neo4j", "networkx", "kuzu", "falkordb"]:
+ raise ProcessingError(
+ f"Unsupported backend: {backend}. "
+ f"Supported: neo4j, networkx, kuzu, falkordb"
+ )
+
+ # Generate node embeddings
+ node_embeddings = self.create_node_embeddings(entities, backend=backend, **options)
+
+ # Generate edge embeddings if relationships provided
+ edge_embeddings = None
+ if relationships:
+ edge_embeddings = self.create_edge_embeddings(
+ relationships, backend=backend, **options
+ )
+
+ # Format nodes with embeddings
+ nodes = []
+ for entity in entities:
+ node_data = entity.copy()
+ node_id = entity.get("id") or entity.get("node_id")
+ if node_id and node_id in node_embeddings:
+ node_data["embedding"] = node_embeddings[node_id]
+ nodes.append(node_data)
+
+ # Format edges with embeddings
+ edges = []
+ if relationships and edge_embeddings:
+ for rel in relationships:
+ edge_data = rel.copy()
+ edge_id = self._get_edge_id(rel)
+ if edge_id and edge_id in edge_embeddings:
+ edge_data["embedding"] = edge_embeddings[edge_id]
+ edges.append(edge_data)
+
+ result = {
+ "node_embeddings": node_embeddings,
+ "edge_embeddings": edge_embeddings,
+ "nodes": nodes,
+ "edges": edges,
+ "backend": backend.lower(),
+ "num_nodes": len(entities),
+ "num_edges": len(relationships) if relationships else 0,
+ }
+
+ # Add backend-specific information
+ result["backend_info"] = self._get_backend_info(backend, **options)
+
+ return result
+
+ def embed_entities(
+ self,
+ entities: List[Dict[str, Any]],
+ text_field: str = "text",
+ **options,
+ ) -> Dict[str, np.ndarray]:
+ """
+ Generate embeddings for graph entities.
+
+ Creates embeddings for entities by extracting text content and generating
+ embeddings using the embedding generator.
+
+ Args:
+ entities: List of entity dictionaries
+ text_field: Field name containing text to embed (default: "text")
+ **options: Additional embedding options
+
+ Returns:
+ Dictionary mapping entity IDs to embedding vectors
+
+ Example:
+ >>> entities = [
+ ... {"id": "e1", "text": "John Doe"},
+ ... {"id": "e2", "text": "Acme Corp"}
+ ... ]
+ >>> embeddings = manager.embed_entities(entities)
+ """
+ entity_embeddings = {}
+
+ # Extract texts for batch processing
+ texts = []
+ entity_ids = []
+ for entity in entities:
+ entity_id = entity.get("id") or entity.get("node_id")
+ if not entity_id:
+ self.logger.warning(f"Entity missing ID, skipping: {entity}")
+ continue
+
+ # Get text content
+ text = entity.get(text_field) or entity.get("content") or entity.get("name")
+ if not text:
+ self.logger.warning(f"Entity {entity_id} missing text content, skipping")
+ continue
+
+ texts.append(str(text))
+ entity_ids.append(entity_id)
+
+ if not texts:
+ self.logger.warning("No valid entities found for embedding")
+ return entity_embeddings
+
+ # Generate embeddings in batch
+ try:
+ embeddings = self.embedding_generator.generate_embeddings(
+ texts, data_type="text", **options
+ )
+
+ # Map embeddings to entity IDs
+ for idx, entity_id in enumerate(entity_ids):
+ if embeddings.ndim == 1:
+ entity_embeddings[entity_id] = embeddings
+ else:
+ entity_embeddings[entity_id] = embeddings[idx]
+
+ except Exception as e:
+ self.logger.error(f"Failed to generate entity embeddings: {e}")
+ raise ProcessingError(f"Failed to generate entity embeddings: {e}")
+
+ return entity_embeddings
+
+ def embed_relationships(
+ self,
+ relationships: List[Dict[str, Any]],
+ text_field: Optional[str] = None,
+ **options,
+ ) -> Dict[str, np.ndarray]:
+ """
+ Generate embeddings for graph relationships.
+
+ Creates embeddings for relationships by extracting relationship text or
+ combining source and target entity information.
+
+ Args:
+ relationships: List of relationship dictionaries
+ text_field: Optional field name containing relationship text
+ If None, combines source and target information
+ **options: Additional embedding options
+
+ Returns:
+ Dictionary mapping relationship IDs to embedding vectors
+
+ Example:
+ >>> relationships = [
+ ... {"source": "e1", "target": "e2", "type": "WORKS_FOR", "text": "works at"}
+ ... ]
+ >>> embeddings = manager.embed_relationships(relationships)
+ """
+ relationship_embeddings = {}
+
+ # Extract texts for batch processing
+ texts = []
+ rel_ids = []
+ for rel in relationships:
+ rel_id = self._get_edge_id(rel)
+ if not rel_id:
+ self.logger.warning(f"Relationship missing ID, skipping: {rel}")
+ continue
+
+ # Get relationship text
+ if text_field and text_field in rel:
+ text = str(rel[text_field])
+ else:
+ # Combine relationship type and source/target info
+ rel_type = rel.get("type", "")
+ source = rel.get("source", "")
+ target = rel.get("target", "")
+ text = f"{rel_type} {source} {target}".strip()
+
+ if not text:
+ self.logger.warning(f"Relationship {rel_id} missing text content, skipping")
+ continue
+
+ texts.append(text)
+ rel_ids.append(rel_id)
+
+ if not texts:
+ self.logger.warning("No valid relationships found for embedding")
+ return relationship_embeddings
+
+ # Generate embeddings in batch
+ try:
+ embeddings = self.embedding_generator.generate_embeddings(
+ texts, data_type="text", **options
+ )
+
+ # Map embeddings to relationship IDs
+ for idx, rel_id in enumerate(rel_ids):
+ if embeddings.ndim == 1:
+ relationship_embeddings[rel_id] = embeddings
+ else:
+ relationship_embeddings[rel_id] = embeddings[idx]
+
+ except Exception as e:
+ self.logger.error(f"Failed to generate relationship embeddings: {e}")
+ raise ProcessingError(f"Failed to generate relationship embeddings: {e}")
+
+ return relationship_embeddings
+
+ def create_node_embeddings(
+ self,
+ entities: List[Dict[str, Any]],
+ backend: str = "neo4j",
+ **options,
+ ) -> Dict[str, np.ndarray]:
+ """
+ Create embeddings for graph nodes (entities).
+
+ Args:
+ entities: List of entity dictionaries
+ backend: Graph DB backend
+ **options: Additional options
+
+ Returns:
+ Dictionary mapping node IDs to embedding vectors
+
+ Example:
+ >>> entities = [{"id": "n1", "text": "Node 1"}]
+ >>> embeddings = manager.create_node_embeddings(entities, backend="neo4j")
+ """
+ return self.embed_entities(entities, **options)
+
+ def create_edge_embeddings(
+ self,
+ relationships: List[Dict[str, Any]],
+ backend: str = "neo4j",
+ **options,
+ ) -> Dict[str, np.ndarray]:
+ """
+ Create embeddings for graph edges (relationships).
+
+ Args:
+ relationships: List of relationship dictionaries
+ backend: Graph DB backend
+ **options: Additional options
+
+ Returns:
+ Dictionary mapping edge IDs to embedding vectors
+
+ Example:
+ >>> relationships = [{"source": "n1", "target": "n2", "type": "RELATES_TO"}]
+ >>> embeddings = manager.create_edge_embeddings(relationships, backend="neo4j")
+ """
+ return self.embed_relationships(relationships, **options)
+
+ def _get_edge_id(self, relationship: Dict[str, Any]) -> Optional[str]:
+ """
+ Get unique ID for a relationship.
+
+ Args:
+ relationship: Relationship dictionary
+
+ Returns:
+ Relationship ID or None if not available
+ """
+ # Try explicit ID fields
+ edge_id = relationship.get("id") or relationship.get("edge_id") or relationship.get("rel_id")
+ if edge_id:
+ return str(edge_id)
+
+ # Generate ID from source, target, and type
+ source = relationship.get("source")
+ target = relationship.get("target")
+ rel_type = relationship.get("type", "")
+
+ if source and target:
+ return f"{source}_{rel_type}_{target}"
+
+ return None
+
+ def _get_backend_info(self, backend: str, **options) -> Dict[str, Any]:
+ """
+ Get backend-specific information.
+
+ Args:
+ backend: Graph DB backend name
+ **options: Additional options
+
+ Returns:
+ Dictionary with backend-specific information
+ """
+ info = {"backend": backend.lower()}
+
+ # Add backend-specific details
+ if backend.lower() == "neo4j":
+ info["database"] = options.get("database", "neo4j")
+ info["label"] = options.get("label", "Node")
+ elif backend.lower() == "networkx":
+ info["graph_type"] = options.get("graph_type", "DiGraph")
+ elif backend.lower() == "kuzu":
+ info["database_path"] = options.get("database_path", "default")
+ elif backend.lower() == "falkordb":
+ info["graph_name"] = options.get("graph_name", "default")
+
+ return info
+
diff --git a/semantica/embeddings/image_embedder.py b/semantica/embeddings/image_embedder.py
deleted file mode 100644
index 708b7cff..00000000
--- a/semantica/embeddings/image_embedder.py
+++ /dev/null
@@ -1,399 +0,0 @@
-"""
-Image Embedder Module
-
-This module provides comprehensive image embedding generation capabilities for the
-Semantica framework, supporting CLIP models and fallback methods for image analysis.
-
-Key Features:
- - CLIP model integration for high-quality image embeddings
- - Batch processing for multiple images
- - Fallback image feature extraction
- - Configurable normalization and device selection
- - Support for various image formats (JPEG, PNG, etc.)
-
-Example Usage:
- >>> from semantica.embeddings import ImageEmbedder
- >>> embedder = ImageEmbedder(model_name="ViT-B/32")
- >>> embedding = embedder.embed_image("image.jpg")
- >>> batch_embeddings = embedder.embed_batch(["img1.jpg", "img2.png"])
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
-
-import numpy as np
-from PIL import Image
-
-from ..utils.exceptions import ProcessingError, ValidationError
-from ..utils.logging import get_logger
-
-try:
- import clip
- import torch
-
- CLIP_AVAILABLE = True
-except ImportError:
- CLIP_AVAILABLE = False
-
-
-class ImageEmbedder:
- """
- Image embedding generator for semantic image representation.
-
- This class provides image embedding generation using CLIP models or fallback
- methods. Supports single images, batch processing, and various image formats.
-
- Features:
- - CLIP model integration for high-quality image embeddings
- - Batch processing for multiple images
- - Fallback image feature extraction (when CLIP unavailable)
- - Configurable normalization and device selection
- - Support for common image formats
-
- Example Usage:
- >>> embedder = ImageEmbedder(
- ... model_name="ViT-B/32",
- ... device="cpu",
- ... normalize=True
- ... )
- >>> embedding = embedder.embed_image("photo.jpg")
- >>> dim = embedder.get_embedding_dimension()
- """
-
- def __init__(
- self,
- model_name: str = "ViT-B/32",
- device: str = "cpu",
- normalize: bool = True,
- **config,
- ):
- """
- Initialize image embedder.
-
- Sets up the embedder with the specified CLIP model and configuration.
- Attempts to load CLIP model, falls back to feature-based embeddings
- if unavailable.
-
- Args:
- model_name: Name of CLIP model to use (default: "ViT-B/32")
- device: Device to run model on - "cpu" or "cuda" (default: "cpu")
- normalize: Whether to normalize embeddings to unit vectors (default: True)
- **config: Additional configuration options
- """
- self.logger = get_logger("image_embedder")
- self.config = config
-
- # Model configuration
- self.model_name = model_name
- self.device = device
- self.normalize = normalize
-
- # Initialize model (will be None if CLIP unavailable)
- self.model = None
- self.preprocess = None
-
- # Initialize progress tracker
- self.progress_tracker = get_progress_tracker()
-
- self._initialize_model()
-
- def _initialize_model(self) -> None:
- """
- Initialize CLIP model.
-
- Attempts to load the specified CLIP model and preprocessing function.
- If unavailable or loading fails, falls back to feature-based embedding
- method. Logs warnings but doesn't raise errors to allow graceful degradation.
- """
- if CLIP_AVAILABLE:
- try:
- self.model, self.preprocess = clip.load(
- self.model_name, device=self.device
- )
- self.logger.info(
- f"Loaded CLIP model: {self.model_name} (device: {self.device})"
- )
- except Exception as e:
- self.logger.warning(
- f"Failed to load CLIP model '{self.model_name}': {e}. "
- "Using fallback image embedding method."
- )
- self.model = None
- self.preprocess = None
- else:
- self.logger.warning(
- "CLIP not available. Install with: pip install clip-by-openai. "
- "Using fallback image embedding method."
- )
-
- def embed_image(self, image_path: Union[str, Path], **options) -> np.ndarray:
- """
- Generate embedding for a single image file.
-
- This method creates a semantic embedding vector for the input image using
- the configured CLIP model or fallback method. Returns a normalized vector
- suitable for similarity calculations.
-
- Args:
- image_path: Path to image file. Supports common formats (JPEG, PNG, etc.)
- **options: Additional embedding options (currently unused)
-
- Returns:
- np.ndarray: 1D embedding vector of shape (embedding_dim,).
- Dimension depends on model (typically 512 for CLIP ViT-B/32).
-
- Raises:
- ValidationError: If image file doesn't exist
- ProcessingError: If image cannot be processed or embedded
-
- Example:
- >>> embedder = ImageEmbedder()
- >>> embedding = embedder.embed_image("photo.jpg")
- >>> print(f"Embedding shape: {embedding.shape}")
- """
- # Track image embedding
- tracking_id = self.progress_tracker.start_tracking(
- file=str(image_path),
- module="embeddings",
- submodule="ImageEmbedder",
- message=f"Generating image embedding: {image_path}",
- )
-
- try:
- image_path = Path(image_path)
-
- # Validate image file exists
- if not image_path.exists():
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="failed",
- message=f"File not found: {image_path}",
- )
- raise ValidationError(
- f"Image file not found: {image_path}. "
- "Please provide a valid image file path."
- )
-
- if not image_path.is_file():
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="failed",
- message=f"Path is not a file: {image_path}",
- )
- raise ValidationError(f"Path is not a file: {image_path}")
-
- self.logger.debug(f"Generating embedding for image: {image_path}")
-
- # Use CLIP if available, otherwise fallback
- if self.model and self.preprocess:
- self.progress_tracker.update_tracking(
- tracking_id, message="Using CLIP model..."
- )
- result = self._embed_with_clip(image_path, **options)
- else:
- self.progress_tracker.update_tracking(
- tracking_id, message="Using fallback method..."
- )
- result = self._embed_fallback(image_path, **options)
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Generated embedding (dim: {len(result)})",
- )
- return result
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise
-
- def _embed_with_clip(self, image_path: Path, **options) -> np.ndarray:
- """
- Embed image using CLIP model.
-
- This method uses the loaded CLIP model to generate high-quality semantic
- embeddings that capture visual content and can be compared with text
- embeddings in the same space.
-
- Args:
- image_path: Path to image file
- **options: Unused (for compatibility)
-
- Returns:
- np.ndarray: CLIP embedding vector
-
- Raises:
- ProcessingError: If image processing or embedding fails
- """
- try:
- # Load and preprocess image
- image = Image.open(image_path)
- image_input = self.preprocess(image).unsqueeze(0).to(self.device)
-
- # Generate embedding (no gradient computation needed)
- with torch.no_grad():
- image_features = self.model.encode_image(image_input)
-
- # Extract embedding and convert to numpy
- embedding = image_features[0].cpu().numpy().astype(np.float32)
-
- # Normalize if requested
- if self.normalize:
- norm = np.linalg.norm(embedding)
- if norm > 0:
- embedding = embedding / norm
-
- self.logger.debug(f"Generated CLIP embedding: shape {embedding.shape}")
- return embedding
-
- except Exception as e:
- error_msg = f"Failed to embed image with CLIP: {e}"
- self.logger.error(error_msg)
- raise ProcessingError(error_msg) from e
-
- def _embed_fallback(self, image_path: Path, **options) -> np.ndarray:
- """
- Fallback embedding using image feature extraction.
-
- This method generates a simple embedding from image pixel data when
- CLIP is not available. Resizes image to fixed size and extracts
- pixel features as embedding.
-
- Note: This is a basic feature extraction method and does not provide
- semantic embeddings. For production use, CLIP is recommended.
-
- Args:
- image_path: Path to image file
- **options: Unused (for compatibility)
-
- Returns:
- np.ndarray: 512-dimensional feature-based embedding vector
-
- Raises:
- ProcessingError: If image cannot be processed
- """
- try:
- # Load image
- image = Image.open(image_path)
-
- # Convert to RGB if necessary
- if image.mode != "RGB":
- image = image.convert("RGB")
-
- # Resize to fixed size for consistent feature extraction
- image = image.resize((224, 224))
-
- # Convert to numpy array
- img_array = np.array(image).astype(np.float32)
-
- # Flatten image to 1D array
- flat = img_array.flatten()
-
- # Downsample to fixed dimension (512)
- if len(flat) > 512:
- # Sample evenly across the flattened array
- step = len(flat) // 512
- embedding = flat[::step][:512]
- else:
- # Pad with zeros if smaller than target dimension
- embedding = np.pad(flat, (0, 512 - len(flat)), "constant")[:512]
-
- # Normalize if requested
- if self.normalize:
- norm = np.linalg.norm(embedding)
- if norm > 0:
- embedding = embedding / norm
-
- self.logger.debug(f"Generated fallback embedding: shape {embedding.shape}")
- return embedding.astype(np.float32)
-
- except Exception as e:
- error_msg = f"Failed to embed image: {e}"
- self.logger.error(error_msg)
- raise ProcessingError(error_msg) from e
-
- def embed_batch(self, image_paths: List[Union[str, Path]], **options) -> np.ndarray:
- """
- Generate embeddings for multiple images in batch.
-
- This method processes multiple images sequentially and returns their
- embeddings as a batch array. Useful for processing image collections.
-
- Args:
- image_paths: List of image file paths. Empty list returns empty array.
- **options: Additional embedding options passed to embed_image()
-
- Returns:
- np.ndarray: 2D array of embeddings with shape (n_images, embedding_dim).
- Returns empty array if input list is empty.
-
- Raises:
- ProcessingError: If any image cannot be processed (processing continues
- for other images, but errors are logged)
-
- Example:
- >>> image_paths = ["img1.jpg", "img2.png", "img3.jpeg"]
- >>> embeddings = embedder.embed_batch(image_paths)
- >>> print(f"Shape: {embeddings.shape}") # (3, embedding_dim)
- """
- if not image_paths:
- self.logger.debug("Empty image list provided, returning empty array")
- return np.array([])
-
- self.logger.info(f"Generating embeddings for {len(image_paths)} image(s)")
-
- embeddings = []
- failed_count = 0
-
- # Process each image
- for image_path in image_paths:
- try:
- embedding = self.embed_image(image_path, **options)
- embeddings.append(embedding)
- except Exception as e:
- failed_count += 1
- self.logger.warning(
- f"Failed to embed image {image_path}: {e}. "
- "Continuing with other images."
- )
-
- if failed_count > 0:
- self.logger.warning(
- f"Failed to embed {failed_count} out of {len(image_paths)} image(s)"
- )
-
- if not embeddings:
- raise ProcessingError(
- f"Failed to embed any images from {len(image_paths)} provided"
- )
-
- self.logger.info(f"Successfully generated {len(embeddings)} embedding(s)")
-
- return np.array(embeddings)
-
- def get_embedding_dimension(self) -> int:
- """
- Get the dimension of embeddings produced by this embedder.
-
- Returns the size of the embedding vectors that will be generated.
- Dimension depends on the model used.
-
- Returns:
- int: Embedding dimension (number of features in embedding vector).
- - CLIP model: Dimension from model (typically 512 for ViT-B/32)
- - Fallback: 512 (feature-based embedding dimension)
-
- Example:
- >>> embedder = ImageEmbedder()
- >>> dim = embedder.get_embedding_dimension()
- >>> print(f"Embedding dimension: {dim}")
- """
- if self.model:
- return self.model.visual.output_dim
- else:
- return 512 # Fallback feature-based embedding dimension
diff --git a/semantica/embeddings/methods.py b/semantica/embeddings/methods.py
index b66bc9da..a66ce625 100644
--- a/semantica/embeddings/methods.py
+++ b/semantica/embeddings/methods.py
@@ -11,31 +11,12 @@ Supported Methods:
Embedding Generation:
- "default": Default embedding generation using EmbeddingGenerator
- "text": Text embedding generation
- - "image": Image embedding generation
- - "audio": Audio embedding generation
- - "multimodal": Multimodal embedding generation
Text Embedding:
- "sentence_transformers": Sentence-transformers model-based embedding
+ - "fastembed": FastEmbed model-based embedding (fast and efficient)
- "fallback": Hash-based fallback embedding
-Image Embedding:
- - "clip": CLIP model-based embedding
- - "fallback": Feature-based fallback embedding
-
-Audio Embedding:
- - "librosa": Librosa feature extraction (MFCC, chroma, spectral contrast, tonnetz)
- - "fallback": Simple fallback embedding
-
-Multimodal Embedding:
- - "concat": Concatenation-based combination
- - "mean": Averaging-based combination
-
-Embedding Optimization:
- - "pca": Principal Component Analysis dimension reduction
- - "quantization": Bit-depth quantization
- - "truncate": Simple dimension truncation
-
Pooling Strategies:
- "mean": Mean pooling
- "max": Max pooling
@@ -51,27 +32,13 @@ Algorithms Used:
Embedding Generation:
- Sentence-transformers Encoding: Transformer-based sentence embedding generation using pre-trained models
- - CLIP Image Encoding: Vision transformer-based image embedding generation for cross-modal understanding
- - Librosa Audio Feature Extraction: Multi-feature audio analysis including:
- * MFCC (Mel-frequency Cepstral Coefficients): 13 coefficients for spectral representation
- * Chroma Features: 12-dimensional pitch class representation
- * Spectral Contrast: 7-dimensional spectral contrast features
- * Tonnetz: 6-dimensional tonal centroid features
- * Temporal Aggregation: Mean pooling across time frames for fixed-size vectors
+ - FastEmbed Encoding: Fast and efficient embedding generation using FastEmbed library
- Hash-based Fallback Embeddings: SHA-256 hash-based deterministic embeddings (128-dimensional)
- Batch Processing: Vectorized processing for multiple items simultaneously
- - Data Type Auto-detection: File extension-based and content-based data type detection
Similarity Calculation:
- Cosine Similarity: Dot product divided by vector norms for normalized similarity (0-1 range)
- Euclidean Similarity: L2 norm distance converted to similarity score (0-1 range)
- - Cross-modal Similarity: Pairwise cosine similarity between different modalities (text-image, image-audio, etc.)
-
-Embedding Optimization:
- - PCA (Principal Component Analysis): Variance-preserving dimension reduction using eigenvalue decomposition
- - Quantization: Bit-depth reduction (8-bit, 16-bit) for memory efficiency with dequantization
- - Dimension Truncation: Simple truncation to first N dimensions
- - Batch Normalization: L2 normalization across batch dimension for unit vectors
Pooling Strategies:
- Mean Pooling: Arithmetic mean across embedding dimension
@@ -80,12 +47,6 @@ Pooling Strategies:
- Attention-based Pooling: Softmax-weighted sum using dot product attention scores
- Hierarchical Pooling: Two-level pooling (chunk-level then global-level mean pooling)
-Multimodal Processing:
- - Dimension Alignment: Truncation/padding to align embedding dimensions across modalities
- - Concatenation: Vector concatenation for combined multimodal embeddings
- - Averaging: Mean aggregation for compact multimodal representation
- - Cross-modal Similarity: Pairwise similarity computation between different input modalities
-
Key Features:
- Multiple embedding generation methods
- Multiple optimization methods
@@ -98,20 +59,16 @@ Key Features:
Main Functions:
- generate_embeddings: Embedding generation wrapper
- embed_text: Text embedding wrapper
- - embed_image: Image embedding wrapper
- - embed_audio: Audio embedding wrapper
- - embed_multimodal: Multimodal embedding wrapper
- - optimize_embeddings: Embedding optimization wrapper
- calculate_similarity: Similarity calculation wrapper
- pool_embeddings: Pooling strategy wrapper
- get_embedding_method: Get embedding method by name
- list_available_methods: List registered methods
Example Usage:
- >>> from semantica.embeddings.methods import embed_text, embed_image, calculate_similarity
- >>> text_emb = embed_text("Hello world", method="sentence_transformers")
- >>> img_emb = embed_image("image.jpg", method="clip")
- >>> similarity = calculate_similarity(text_emb, img_emb, method="cosine")
+ >>> from semantica.embeddings.methods import embed_text, calculate_similarity
+ >>> text_emb1 = embed_text("Hello world", method="sentence_transformers")
+ >>> text_emb2 = embed_text("Hi there", method="fastembed")
+ >>> similarity = calculate_similarity(text_emb1, text_emb2, method="cosine")
>>> from semantica.embeddings.methods import get_embedding_method
>>> method = get_embedding_method("text", "custom_method")
"""
@@ -123,12 +80,8 @@ import numpy as np
from ..utils.exceptions import ConfigurationError, ProcessingError
from ..utils.logging import get_logger
-from .audio_embedder import AudioEmbedder
from .config import embeddings_config
from .embedding_generator import EmbeddingGenerator
-from .embedding_optimizer import EmbeddingOptimizer
-from .image_embedder import ImageEmbedder
-from .multimodal_embedder import MultimodalEmbedder
from .pooling_strategies import PoolingStrategyFactory
from .registry import method_registry
from .text_embedder import TextEmbedder
@@ -149,12 +102,10 @@ def generate_embeddings(
Args:
data: Input data - can be text string, file path, or list of texts/paths
- data_type: Data type - "text", "image", "audio" (auto-detected if None)
+ data_type: Data type - "text" (auto-detected if None)
method: Generation method (default: "default")
- "default": Use EmbeddingGenerator with auto-detection
- "text": Text embedding generation
- - "image": Image embedding generation
- - "audio": Audio embedding generation
**kwargs: Additional options passed to embedder
Returns:
@@ -181,10 +132,6 @@ def generate_embeddings(
return generator.generate_embeddings(data, data_type=data_type, **kwargs)
elif method == "text":
return embed_text(data, **kwargs)
- elif method == "image":
- return embed_image(data, **kwargs)
- elif method == "audio":
- return embed_audio(data, **kwargs)
else:
raise ProcessingError(f"Unknown generation method: {method}")
@@ -205,6 +152,7 @@ def embed_text(
text: Input text string or list of texts
method: Text embedding method (default: "sentence_transformers")
- "sentence_transformers": Sentence-transformers model-based embedding
+ - "fastembed": FastEmbed model-based embedding (fast and efficient)
- "fallback": Hash-based fallback embedding
**kwargs: Additional options passed to TextEmbedder
@@ -231,6 +179,15 @@ def embed_text(
config = embeddings_config.get_method_config("text")
config.update(kwargs)
+ # Set method if specified
+ if method == "fastembed":
+ config["method"] = "fastembed"
+ # Use FastEmbed default model if not specified
+ if "model_name" not in config:
+ config["model_name"] = "BAAI/bge-small-en-v1.5"
+ elif method == "sentence_transformers":
+ config["method"] = "sentence_transformers"
+
embedder = TextEmbedder(**config)
if isinstance(text, list):
@@ -243,237 +200,6 @@ def embed_text(
raise
-def embed_image(
- image_path: Union[str, Path, List[Union[str, Path]]], method: str = "clip", **kwargs
-) -> np.ndarray:
- """
- Generate image embeddings (convenience function).
-
- This is a user-friendly wrapper that generates image embeddings using the specified method.
-
- Args:
- image_path: Path to image file or list of paths
- method: Image embedding method (default: "clip")
- - "clip": CLIP model-based embedding
- - "fallback": Feature-based fallback embedding
- **kwargs: Additional options passed to ImageEmbedder
-
- Returns:
- np.ndarray: Image embeddings (1D for single image, 2D for batch)
-
- Examples:
- >>> from semantica.embeddings.methods import embed_image
- >>> emb = embed_image("image.jpg", method="clip")
- >>> embs = embed_image(["img1.jpg", "img2.png"], method="clip")
- """
- # Check for custom method in registry
- custom_method = method_registry.get("image", method)
- if custom_method:
- try:
- return custom_method(image_path, **kwargs)
- except Exception as e:
- logger.warning(
- f"Custom method {method} failed: {e}, falling back to default"
- )
-
- try:
- # Get config
- config = embeddings_config.get_method_config("image")
- config.update(kwargs)
-
- embedder = ImageEmbedder(**config)
-
- if isinstance(image_path, list):
- return embedder.embed_batch(image_path, **kwargs)
- else:
- return embedder.embed_image(image_path, **kwargs)
-
- except Exception as e:
- logger.error(f"Failed to embed image: {e}")
- raise
-
-
-def embed_audio(
- audio_path: Union[str, Path, List[Union[str, Path]]],
- method: str = "librosa",
- **kwargs,
-) -> np.ndarray:
- """
- Generate audio embeddings (convenience function).
-
- This is a user-friendly wrapper that generates audio embeddings using the specified method.
-
- Args:
- audio_path: Path to audio file or list of paths
- method: Audio embedding method (default: "librosa")
- - "librosa": Librosa feature extraction (MFCC, chroma, spectral contrast, tonnetz)
- - "fallback": Simple fallback embedding
- **kwargs: Additional options passed to AudioEmbedder
-
- Returns:
- np.ndarray: Audio embeddings (1D for single audio, 2D for batch)
-
- Examples:
- >>> from semantica.embeddings.methods import embed_audio
- >>> emb = embed_audio("audio.wav", method="librosa")
- >>> embs = embed_audio(["audio1.wav", "audio2.mp3"], method="librosa")
- """
- # Check for custom method in registry
- custom_method = method_registry.get("audio", method)
- if custom_method:
- try:
- return custom_method(audio_path, **kwargs)
- except Exception as e:
- logger.warning(
- f"Custom method {method} failed: {e}, falling back to default"
- )
-
- try:
- # Get config
- config = embeddings_config.get_method_config("audio")
- config.update(kwargs)
-
- embedder = AudioEmbedder(**config)
-
- if isinstance(audio_path, list):
- return embedder.embed_batch(audio_path, **kwargs)
- else:
- return embedder.embed_audio(audio_path, **kwargs)
-
- except Exception as e:
- logger.error(f"Failed to embed audio: {e}")
- raise
-
-
-def embed_multimodal(
- text: Optional[str] = None,
- image_path: Optional[Union[str, Path]] = None,
- audio_path: Optional[Union[str, Path]] = None,
- method: str = "concat",
- **kwargs,
-) -> np.ndarray:
- """
- Generate multimodal embeddings (convenience function).
-
- This is a user-friendly wrapper that generates multimodal embeddings using the specified method.
-
- Args:
- text: Input text string (optional)
- image_path: Path to image file (optional)
- audio_path: Path to audio file (optional)
- method: Multimodal combination method (default: "concat")
- - "concat": Concatenation-based combination
- - "mean": Averaging-based combination
- **kwargs: Additional options passed to MultimodalEmbedder
-
- Returns:
- np.ndarray: Multimodal embedding vector
-
- Examples:
- >>> from semantica.embeddings.methods import embed_multimodal
- >>> emb = embed_multimodal(
- ... text="A cat",
- ... image_path="cat.jpg",
- ... method="concat"
- ... )
- """
- # Check for custom method in registry
- custom_method = method_registry.get("multimodal", method)
- if custom_method:
- try:
- return custom_method(text, image_path, audio_path, **kwargs)
- except Exception as e:
- logger.warning(
- f"Custom method {method} failed: {e}, falling back to default"
- )
-
- try:
- # Get config
- config = embeddings_config.get_method_config("multimodal")
- config.update(kwargs)
-
- embedder = MultimodalEmbedder(**config)
-
- return embedder.embed_multimodal(
- text=text,
- image_path=image_path,
- audio_path=audio_path,
- combine_method=method,
- **kwargs,
- )
-
- except Exception as e:
- logger.error(f"Failed to embed multimodal: {e}")
- raise
-
-
-def optimize_embeddings(
- embeddings: np.ndarray,
- method: str = "pca",
- target_dim: Optional[int] = None,
- **kwargs,
-) -> np.ndarray:
- """
- Optimize embeddings (convenience function).
-
- This is a user-friendly wrapper that optimizes embeddings using the specified method.
-
- Args:
- embeddings: Input embeddings array
- method: Optimization method (default: "pca")
- - "pca": Principal Component Analysis dimension reduction
- - "quantization": Bit-depth quantization
- - "truncate": Simple dimension truncation
- target_dim: Target dimension for reduction (required for pca/truncate)
- **kwargs: Additional options passed to EmbeddingOptimizer
-
- Returns:
- np.ndarray: Optimized embeddings
-
- Examples:
- >>> from semantica.embeddings.methods import optimize_embeddings
- >>> compressed = optimize_embeddings(embeddings, method="pca", target_dim=64)
- >>> quantized = optimize_embeddings(embeddings, method="quantization", bits=8)
- """
- # Check for custom method in registry
- custom_method = method_registry.get("optimization", method)
- if custom_method:
- try:
- return custom_method(embeddings, target_dim=target_dim, **kwargs)
- except Exception as e:
- logger.warning(
- f"Custom method {method} failed: {e}, falling back to default"
- )
-
- try:
- # Get config
- config = embeddings_config.get_method_config("optimization")
- config.update(kwargs)
-
- optimizer = EmbeddingOptimizer(**config)
-
- if method == "pca":
- if target_dim is None:
- raise ProcessingError("target_dim required for PCA method")
- return optimizer.compress(
- embeddings, target_dim=target_dim, method="pca", **kwargs
- )
- elif method == "quantization":
- return optimizer.compress(embeddings, method="quantization", **kwargs)
- elif method == "truncate":
- if target_dim is None:
- raise ProcessingError("target_dim required for truncate method")
- return optimizer.reduce_dimensions(
- embeddings, target_dim=target_dim, method="truncate", **kwargs
- )
- else:
- raise ProcessingError(f"Unknown optimization method: {method}")
-
- except Exception as e:
- logger.error(f"Failed to optimize embeddings: {e}")
- raise
-
-
def calculate_similarity(
embedding1: np.ndarray, embedding2: np.ndarray, method: str = "cosine", **kwargs
) -> float:
@@ -569,7 +295,7 @@ def get_embedding_method(task: str, name: str) -> Optional[Callable]:
Get a registered embedding method.
Args:
- task: Task type ("generation", "text", "image", "audio", "multimodal", "optimization", "pooling", "provider", "similarity")
+ task: Task type ("generation", "text", "image", "pooling", "provider", "similarity")
name: Method name
Returns:
@@ -602,22 +328,53 @@ def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:
return method_registry.list_all(task)
+def check_available_providers() -> Dict[str, bool]:
+ """
+ Check which embedding providers are available in the environment.
+
+ Returns:
+ dict: Dictionary mapping provider names to availability status
+
+ Example:
+ >>> from semantica.embeddings.methods import check_available_providers
+ >>> providers = check_available_providers()
+ >>> if providers["sentence_transformers"]:
+ ... print("Sentence Transformers is available")
+ >>> if providers["fastembed"]:
+ ... print("FastEmbed is available")
+ """
+ providers = {}
+
+ # Check sentence-transformers
+ try:
+ import sentence_transformers
+ providers["sentence_transformers"] = True
+ except ImportError:
+ providers["sentence_transformers"] = False
+
+ # Check FastEmbed
+ try:
+ import fastembed
+ providers["fastembed"] = True
+ except ImportError:
+ providers["fastembed"] = False
+
+ # Check OpenAI
+ try:
+ import openai
+ providers["openai"] = True
+ except ImportError:
+ providers["openai"] = False
+
+ return providers
+
+
# Register default methods
method_registry.register("generation", "default", generate_embeddings)
method_registry.register("generation", "text", generate_embeddings)
-method_registry.register("generation", "image", generate_embeddings)
-method_registry.register("generation", "audio", generate_embeddings)
method_registry.register("text", "sentence_transformers", embed_text)
+method_registry.register("text", "fastembed", embed_text)
method_registry.register("text", "fallback", embed_text)
-method_registry.register("image", "clip", embed_image)
-method_registry.register("image", "fallback", embed_image)
-method_registry.register("audio", "librosa", embed_audio)
-method_registry.register("audio", "fallback", embed_audio)
-method_registry.register("multimodal", "concat", embed_multimodal)
-method_registry.register("multimodal", "mean", embed_multimodal)
-method_registry.register("optimization", "pca", optimize_embeddings)
-method_registry.register("optimization", "quantization", optimize_embeddings)
-method_registry.register("optimization", "truncate", optimize_embeddings)
method_registry.register("similarity", "cosine", calculate_similarity)
method_registry.register("similarity", "euclidean", calculate_similarity)
method_registry.register("pooling", "mean", pool_embeddings)
diff --git a/semantica/embeddings/multimodal_embedder.py b/semantica/embeddings/multimodal_embedder.py
deleted file mode 100644
index 4ba684f5..00000000
--- a/semantica/embeddings/multimodal_embedder.py
+++ /dev/null
@@ -1,481 +0,0 @@
-"""
-Multimodal Embedder Module
-
-This module provides comprehensive cross-modal embedding generation capabilities
-for the Semantica framework, enabling unified embedding spaces for text, image,
-and audio content.
-
-Key Features:
- - Cross-modal embedding generation (text, image, audio)
- - Multimodal embedding combination strategies
- - Cross-modal similarity computation
- - Dimension alignment across modalities
- - Configurable combination methods (concatenation, averaging)
-
-Example Usage:
- >>> from semantica.embeddings import MultimodalEmbedder
- >>> embedder = MultimodalEmbedder()
- >>> embedding = embedder.embed_multimodal(
- ... text="A cat sitting on a mat",
- ... image_path="cat.jpg"
- ... )
- >>> similarity = embedder.compute_cross_modal_similarity(
- ... text="A cat",
- ... image_path="cat.jpg"
- ... )
-
-Author: Semantica Contributors
-License: MIT
-"""
-
-from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
-
-import numpy as np
-
-from ..utils.exceptions import ProcessingError
-from ..utils.logging import get_logger
-from ..utils.progress_tracker import get_progress_tracker
-from .audio_embedder import AudioEmbedder
-from .image_embedder import ImageEmbedder
-from .text_embedder import TextEmbedder
-
-
-class MultimodalEmbedder:
- """
- Multimodal embedding generator for cross-modal semantic representation.
-
- This class provides unified embedding generation across multiple modalities
- (text, image, audio), enabling cross-modal similarity and combined embeddings.
-
- Features:
- - Cross-modal embedding generation
- - Multimodal embedding combination (concatenation, averaging)
- - Cross-modal similarity computation
- - Automatic dimension alignment
- - Configurable normalization
-
- Example Usage:
- >>> embedder = MultimodalEmbedder(
- ... align_modalities=True,
- ... normalize=True
- ... )
- >>> # Combined embedding from text and image
- >>> embedding = embedder.embed_multimodal(
- ... text="A cat",
- ... image_path="cat.jpg"
- ... )
- >>> # Cross-modal similarity
- >>> similarity = embedder.compute_cross_modal_similarity(
- ... text="A cat",
- ... image_path="cat.jpg"
- ... )
- """
-
- def __init__(self, align_modalities: bool = True, normalize: bool = True, **config):
- """
- Initialize multimodal embedder.
-
- Sets up embedders for each modality (text, image, audio) and configures
- cross-modal processing options.
-
- Args:
- align_modalities: Whether to align embedding dimensions across modalities
- before combination (default: True)
- normalize: Whether to normalize embeddings to unit vectors (default: True)
- **config: Additional configuration options:
- - text: Text embedder configuration
- - image: Image embedder configuration
- - audio: Audio embedder configuration
- """
- self.logger = get_logger("multimodal_embedder")
- self.config = config
-
- # Cross-modal configuration
- self.align_modalities = align_modalities
- self.normalize = normalize
-
- # Initialize modality-specific embedders
- text_config = config.get("text", {})
- image_config = config.get("image", {})
- audio_config = config.get("audio", {})
-
- self.text_embedder = TextEmbedder(**text_config)
- self.image_embedder = ImageEmbedder(**image_config)
- self.audio_embedder = AudioEmbedder(**audio_config)
-
- # Initialize progress tracker
- self.progress_tracker = get_progress_tracker()
-
- self.logger.debug(
- f"Multimodal embedder initialized "
- f"(align_modalities={align_modalities}, normalize={normalize})"
- )
-
- def embed_text(self, text: str, **options) -> np.ndarray:
- """
- Generate embedding for text using text embedder.
-
- Convenience method that delegates to the text embedder.
-
- Args:
- text: Input text string to embed
- **options: Embedding options passed to text embedder
-
- Returns:
- np.ndarray: Text embedding vector
- """
- return self.text_embedder.embed_text(text, **options)
-
- def embed_image(self, image_path: Union[str, Path], **options) -> np.ndarray:
- """
- Generate embedding for image using image embedder.
-
- Convenience method that delegates to the image embedder.
-
- Args:
- image_path: Path to image file
- **options: Embedding options passed to image embedder
-
- Returns:
- np.ndarray: Image embedding vector
- """
- return self.image_embedder.embed_image(image_path, **options)
-
- def embed_audio(self, audio_path: Union[str, Path], **options) -> np.ndarray:
- """
- Generate embedding for audio using audio embedder.
-
- Convenience method that delegates to the audio embedder.
-
- Args:
- audio_path: Path to audio file
- **options: Embedding options passed to audio embedder
-
- Returns:
- np.ndarray: Audio embedding vector
- """
- return self.audio_embedder.embed_audio(audio_path, **options)
-
- def embed_multimodal(
- self,
- text: Optional[str] = None,
- image_path: Optional[Union[str, Path]] = None,
- audio_path: Optional[Union[str, Path]] = None,
- combine_method: str = "concat",
- **options,
- ) -> np.ndarray:
- """
- Generate multimodal embedding from multiple input modalities.
-
- This method combines embeddings from different modalities (text, image, audio)
- into a single unified embedding vector. Supports concatenation or averaging
- as combination strategies.
-
- Combination Methods:
- - "concat": Concatenate embeddings (default) - preserves all information
- - "mean": Average embeddings - creates compact representation
-
- Args:
- text: Input text string (optional)
- image_path: Path to image file (optional)
- audio_path: Path to audio file (optional)
- combine_method: Method to combine embeddings - "concat" or "mean" (default: "concat")
- **options: Additional embedding options passed to individual embedders
-
- Returns:
- np.ndarray: Combined multimodal embedding vector.
- If only one modality provided, returns that embedding directly.
-
- Raises:
- ProcessingError: If no inputs provided or embedding generation fails
-
- Example:
- >>> # Text + Image
- >>> embedding = embedder.embed_multimodal(
- ... text="A cat",
- ... image_path="cat.jpg",
- ... combine_method="concat"
- ... )
- >>> # All three modalities
- >>> embedding = embedder.embed_multimodal(
- ... text="Speech about cats",
- ... image_path="cat.jpg",
- ... audio_path="speech.wav"
- ... )
- """
- # Track multimodal embedding
- modalities = []
- if text:
- modalities.append("text")
- if image_path:
- modalities.append("image")
- if audio_path:
- modalities.append("audio")
-
- tracking_id = self.progress_tracker.start_tracking(
- file=None,
- module="embeddings",
- submodule="MultimodalEmbedder",
- message=f"Generating multimodal embedding ({', '.join(modalities)})",
- )
-
- try:
- embeddings = []
-
- # Embed each provided modality
- if text:
- self.logger.debug("Embedding text modality")
- self.progress_tracker.update_tracking(
- tracking_id, message="Generating text embedding..."
- )
- text_emb = self.embed_text(text, **options)
- embeddings.append(text_emb)
-
- if image_path:
- self.logger.debug(f"Embedding image modality: {image_path}")
- self.progress_tracker.update_tracking(
- tracking_id, message="Generating image embedding..."
- )
- img_emb = self.embed_image(image_path, **options)
- embeddings.append(img_emb)
-
- if audio_path:
- self.logger.debug(f"Embedding audio modality: {audio_path}")
- self.progress_tracker.update_tracking(
- tracking_id, message="Generating audio embedding..."
- )
- audio_emb = self.embed_audio(audio_path, **options)
- embeddings.append(audio_emb)
-
- # Validate at least one input provided
- if not embeddings:
- raise ProcessingError(
- "At least one input (text, image, or audio) is required "
- "for multimodal embedding"
- )
-
- # If only one modality, return it directly
- if len(embeddings) == 1:
- self.logger.debug("Single modality provided, returning directly")
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Generated {modalities[0]} embedding",
- )
- return embeddings[0]
-
- # Align dimensions if needed (ensures all embeddings have same dimension)
- if self.align_modalities:
- self.logger.debug("Aligning embedding dimensions across modalities")
- self.progress_tracker.update_tracking(
- tracking_id, message="Aligning embedding dimensions..."
- )
- embeddings = self._align_dimensions(embeddings)
-
- # Combine embeddings using specified method
- self.progress_tracker.update_tracking(
- tracking_id, message=f"Combining embeddings using {combine_method}..."
- )
- if combine_method == "concat":
- # Concatenate: preserves all information, larger dimension
- combined = np.concatenate(embeddings)
- self.logger.debug(
- f"Combined {len(embeddings)} embeddings via concatenation: "
- f"shape {combined.shape}"
- )
- elif combine_method == "mean":
- # Average: compact representation, same dimension as inputs
- combined = np.mean(embeddings, axis=0)
- self.logger.debug(
- f"Combined {len(embeddings)} embeddings via averaging: "
- f"shape {combined.shape}"
- )
- else:
- raise ProcessingError(
- f"Unsupported combine_method: {combine_method}. "
- "Use 'concat' or 'mean'."
- )
-
- # Normalize if requested
- if self.normalize:
- self.progress_tracker.update_tracking(
- tracking_id, message="Normalizing embedding..."
- )
- norm = np.linalg.norm(combined)
- if norm > 0:
- combined = combined / norm
-
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Generated multimodal embedding (dim: {len(combined)})",
- )
- return combined
-
- except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
- raise
-
- def _align_dimensions(self, embeddings: List[np.ndarray]) -> List[np.ndarray]:
- """
- Align embedding dimensions across different modalities.
-
- This method ensures all embeddings have the same dimension by truncating
- larger embeddings or padding smaller ones. Uses the minimum dimension
- as the target to preserve information from all modalities.
-
- Args:
- embeddings: List of embedding vectors with potentially different dimensions
-
- Returns:
- List of np.ndarray: Aligned embeddings, all with same dimension
- """
- if not embeddings:
- return []
-
- # Find target dimension (use minimum to preserve information)
- dims = [emb.shape[0] for emb in embeddings]
- target_dim = min(dims)
-
- self.logger.debug(
- f"Aligning embeddings: dimensions {dims} -> target {target_dim}"
- )
-
- aligned = []
- for i, emb in enumerate(embeddings):
- if emb.shape[0] == target_dim:
- # Already correct dimension
- aligned.append(emb)
- elif emb.shape[0] > target_dim:
- # Truncate: take first target_dim elements
- aligned.append(emb[:target_dim])
- self.logger.debug(
- f"Truncated embedding {i} from {emb.shape[0]} to {target_dim}"
- )
- else:
- # Pad: add zeros to reach target dimension
- padding = target_dim - emb.shape[0]
- padded = np.pad(emb, (0, padding), "constant")
- aligned.append(padded)
- self.logger.debug(
- f"Padded embedding {i} from {emb.shape[0]} to {target_dim}"
- )
-
- return aligned
-
- def compute_cross_modal_similarity(
- self,
- text: Optional[str] = None,
- image_path: Optional[Union[str, Path]] = None,
- audio_path: Optional[Union[str, Path]] = None,
- **options,
- ) -> float:
- """
- Compute similarity between different input modalities.
-
- This method calculates the semantic similarity between embeddings from
- different modalities (e.g., text and image, image and audio). Useful for
- cross-modal retrieval and matching tasks.
-
- The method computes pairwise cosine similarities between all provided
- modalities and returns the average similarity score.
-
- Args:
- text: Input text string (optional)
- image_path: Path to image file (optional)
- audio_path: Path to audio file (optional)
- **options: Additional embedding options passed to embedders
-
- Returns:
- float: Average pairwise similarity score between modalities (0-1).
- Higher values indicate greater semantic similarity.
-
- Raises:
- ProcessingError: If fewer than two modalities provided or embedding fails
-
- Example:
- >>> # Text-Image similarity
- >>> similarity = embedder.compute_cross_modal_similarity(
- ... text="A cat sitting on a mat",
- ... image_path="cat.jpg"
- ... )
- >>> print(f"Text-Image similarity: {similarity:.3f}")
- >>> # All three modalities
- >>> similarity = embedder.compute_cross_modal_similarity(
- ... text="Speech about cats",
- ... image_path="cat.jpg",
- ... audio_path="speech.wav"
- ... )
- """
- embeddings = {}
-
- # Generate embeddings for each provided modality
- if text:
- self.logger.debug("Computing text embedding for similarity")
- embeddings["text"] = self.embed_text(text, **options)
-
- if image_path:
- self.logger.debug(f"Computing image embedding for similarity: {image_path}")
- embeddings["image"] = self.embed_image(image_path, **options)
-
- if audio_path:
- self.logger.debug(f"Computing audio embedding for similarity: {audio_path}")
- embeddings["audio"] = self.embed_audio(audio_path, **options)
-
- # Validate at least two modalities provided
- if len(embeddings) < 2:
- raise ProcessingError(
- f"At least two modalities required for cross-modal similarity. "
- f"Provided: {list(embeddings.keys())}"
- )
-
- # Get list of embeddings for pairwise comparison
- emb_list = list(embeddings.values())
-
- # Align dimensions for fair comparison
- aligned = self._align_dimensions(emb_list)
-
- # Compute pairwise cosine similarities
- similarities = []
- for i in range(len(aligned)):
- for j in range(i + 1, len(aligned)):
- similarity = self._cosine_similarity(aligned[i], aligned[j])
- similarities.append(similarity)
- self.logger.debug(
- f"Similarity between modality {i} and {j}: {similarity:.3f}"
- )
-
- # Return average similarity
- avg_similarity = np.mean(similarities) if similarities else 0.0
- self.logger.debug(f"Average cross-modal similarity: {avg_similarity:.3f}")
-
- return avg_similarity
-
- def _cosine_similarity(self, emb1: np.ndarray, emb2: np.ndarray) -> float:
- """
- Compute cosine similarity between two embedding vectors.
-
- Cosine similarity measures the cosine of the angle between two vectors,
- providing a normalized similarity score between -1 and 1. For normalized
- embeddings, this ranges from 0 to 1.
-
- Args:
- emb1: First embedding vector
- emb2: Second embedding vector
-
- Returns:
- float: Cosine similarity score (0-1 for normalized embeddings).
- Returns 0.0 if either vector has zero norm.
- """
- dot_product = np.dot(emb1, emb2)
- norm1 = np.linalg.norm(emb1)
- norm2 = np.linalg.norm(emb2)
-
- # Handle zero-norm vectors
- if norm1 == 0 or norm2 == 0:
- return 0.0
-
- return dot_product / (norm1 * norm2)
diff --git a/semantica/embeddings/provider_adapters.py b/semantica/embeddings/provider_adapters.py
index 0900c327..e32a8bcb 100644
--- a/semantica/embeddings/provider_adapters.py
+++ b/semantica/embeddings/provider_adapters.py
@@ -191,6 +191,81 @@ class LlamaAdapter(ProviderAdapter):
return placeholder
+class FastEmbedAdapter(ProviderAdapter):
+ """FastEmbed adapter for fast and efficient embedding generation."""
+
+ def __init__(self, **config):
+ """Initialize FastEmbed adapter."""
+ super().__init__(**config)
+
+ self.model_name = config.get("model_name", "BAAI/bge-small-en-v1.5")
+ self.model = None
+
+ self._initialize_model()
+
+ def _initialize_model(self):
+ """Initialize FastEmbed model."""
+ try:
+ from fastembed import TextEmbedding
+
+ self.model = TextEmbedding(model_name=self.model_name)
+ self.logger.info(f"Loaded FastEmbed model: {self.model_name}")
+ except ImportError:
+ self.logger.warning(
+ "fastembed not available. Install with: pip install fastembed"
+ )
+ except Exception as e:
+ self.logger.warning(f"Failed to load FastEmbed model: {e}")
+
+ def embed(self, text: str, **options) -> np.ndarray:
+ """
+ Generate embedding using FastEmbed.
+
+ Args:
+ text: Input text
+ **options: Embedding options
+
+ Returns:
+ np.ndarray: Embedding vector
+ """
+ if not self.model:
+ raise ProcessingError("FastEmbed model not initialized")
+
+ try:
+ # FastEmbed returns an iterator, get first item
+ embeddings = list(self.model.embed([text]))
+ if embeddings:
+ embedding = np.array(embeddings[0], dtype=np.float32)
+ return embedding
+ else:
+ raise ProcessingError("FastEmbed returned empty embedding")
+ except Exception as e:
+ self.logger.error(f"Failed to get FastEmbed embedding: {e}")
+ raise ProcessingError(f"Failed to get FastEmbed embedding: {e}")
+
+ def embed_batch(self, texts: List[str], **options) -> np.ndarray:
+ """
+ Generate embeddings for multiple texts using FastEmbed's efficient batch processing.
+
+ Args:
+ texts: List of texts
+ **options: Embedding options
+
+ Returns:
+ np.ndarray: Array of embeddings
+ """
+ if not self.model:
+ raise ProcessingError("FastEmbed model not initialized")
+
+ try:
+ # FastEmbed efficiently handles batch processing
+ embeddings = list(self.model.embed(texts))
+ return np.array(embeddings, dtype=np.float32)
+ except Exception as e:
+ self.logger.error(f"Failed to get FastEmbed batch embeddings: {e}")
+ raise ProcessingError(f"Failed to get FastEmbed batch embeddings: {e}")
+
+
class ProviderAdapterFactory:
"""Factory for creating provider adapters."""
@@ -200,13 +275,18 @@ class ProviderAdapterFactory:
Create provider adapter.
Args:
- provider: Provider name ("openai", "bge", "llama")
+ provider: Provider name ("openai", "bge", "llama", "fastembed")
**config: Provider configuration
Returns:
ProviderAdapter: Provider adapter instance
"""
- providers = {"openai": OpenAIAdapter, "bge": BGEAdapter, "llama": LlamaAdapter}
+ providers = {
+ "openai": OpenAIAdapter,
+ "bge": BGEAdapter,
+ "llama": LlamaAdapter,
+ "fastembed": FastEmbedAdapter,
+ }
adapter_class = providers.get(provider.lower())
if not adapter_class:
diff --git a/semantica/embeddings/text_embedder.py b/semantica/embeddings/text_embedder.py
index 7d42faad..baa3fd82 100644
--- a/semantica/embeddings/text_embedder.py
+++ b/semantica/embeddings/text_embedder.py
@@ -37,6 +37,13 @@ try:
except ImportError:
SENTENCE_TRANSFORMERS_AVAILABLE = False
+try:
+ from fastembed import TextEmbedding
+
+ FASTEMBED_AVAILABLE = True
+except ImportError:
+ FASTEMBED_AVAILABLE = False
+
class TextEmbedder:
"""
@@ -68,20 +75,24 @@ class TextEmbedder:
model_name: str = "all-MiniLM-L6-v2",
device: str = "cpu",
normalize: bool = True,
+ method: str = "sentence_transformers",
**config,
):
"""
Initialize text embedder.
Sets up the embedder with the specified model and configuration.
- Attempts to load sentence-transformers model, falls back to hash-based
- embeddings if unavailable.
+ Supports both sentence-transformers and FastEmbed models.
Args:
- model_name: Name of sentence-transformers model to use
- (default: "all-MiniLM-L6-v2")
+ model_name: Name of model to use
+ (default: "all-MiniLM-L6-v2" for sentence-transformers,
+ "BAAI/bge-small-en-v1.5" for FastEmbed)
device: Device to run model on - "cpu" or "cuda" (default: "cpu")
+ Note: FastEmbed doesn't use device parameter
normalize: Whether to normalize embeddings to unit vectors (default: True)
+ method: Embedding method - "sentence_transformers" or "fastembed"
+ (default: "sentence_transformers")
**config: Additional configuration options
"""
self.logger = get_logger("text_embedder")
@@ -91,9 +102,11 @@ class TextEmbedder:
self.model_name = model_name
self.device = device
self.normalize = normalize
+ self.method = method.lower()
- # Initialize model (will be None if sentence-transformers unavailable)
+ # Initialize models (will be None if unavailable)
self.model = None
+ self.fastembed_model = None
# Initialize progress tracker
self.progress_tracker = get_progress_tracker()
@@ -104,29 +117,54 @@ class TextEmbedder:
"""
Initialize embedding model.
- Attempts to load the specified sentence-transformers model. If unavailable
- or loading fails, falls back to hash-based embedding method. Logs warnings
- but doesn't raise errors to allow graceful degradation.
+ Attempts to load the specified model (sentence-transformers or FastEmbed).
+ If unavailable or loading fails, falls back to hash-based embedding method.
+ Logs warnings but doesn't raise errors to allow graceful degradation.
"""
- if SENTENCE_TRANSFORMERS_AVAILABLE:
- try:
- self.model = SentenceTransformer(self.model_name, device=self.device)
- self.logger.info(
- f"Loaded sentence-transformers model: {self.model_name} "
- f"(device: {self.device})"
- )
- except Exception as e:
+ if self.method == "fastembed":
+ if FASTEMBED_AVAILABLE:
+ try:
+ # Use model_name from config or default for FastEmbed
+ fastembed_model_name = self.config.get(
+ "fastembed_model_name", self.model_name
+ )
+ self.fastembed_model = TextEmbedding(model_name=fastembed_model_name)
+ self.logger.info(
+ f"Loaded FastEmbed model: {fastembed_model_name}"
+ )
+ except Exception as e:
+ self.logger.warning(
+ f"Failed to load FastEmbed model '{self.model_name}': {e}. "
+ "Using fallback embedding method."
+ )
+ self.fastembed_model = None
+ else:
self.logger.warning(
- f"Failed to load model '{self.model_name}': {e}. "
+ "fastembed not available. "
+ "Install with: pip install fastembed. "
"Using fallback embedding method."
)
- self.model = None
else:
- self.logger.warning(
- "sentence-transformers not available. "
- "Install with: pip install sentence-transformers. "
- "Using fallback embedding method."
- )
+ # Default to sentence-transformers
+ if SENTENCE_TRANSFORMERS_AVAILABLE:
+ try:
+ self.model = SentenceTransformer(self.model_name, device=self.device)
+ self.logger.info(
+ f"Loaded sentence-transformers model: {self.model_name} "
+ f"(device: {self.device})"
+ )
+ except Exception as e:
+ self.logger.warning(
+ f"Failed to load model '{self.model_name}': {e}. "
+ "Using fallback embedding method."
+ )
+ self.model = None
+ else:
+ self.logger.warning(
+ "sentence-transformers not available. "
+ "Install with: pip install sentence-transformers. "
+ "Using fallback embedding method."
+ )
def embed_text(self, text: str, **options) -> np.ndarray:
"""
@@ -169,7 +207,12 @@ class TextEmbedder:
raise ProcessingError("Text cannot be empty or whitespace-only")
# Use model if available, otherwise fallback
- if self.model:
+ if self.fastembed_model:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Using FastEmbed model..."
+ )
+ result = self._embed_with_fastembed(text, **options)
+ elif self.model:
self.progress_tracker.update_tracking(
tracking_id, message="Using sentence-transformers model..."
)
@@ -213,6 +256,32 @@ class TextEmbedder:
return embeddings[0]
+ def _embed_with_fastembed(self, text: str, **options) -> np.ndarray:
+ """
+ Embed text using FastEmbed model.
+
+ This method uses the loaded FastEmbed model to generate
+ high-quality semantic embeddings efficiently.
+
+ Args:
+ text: Input text to embed
+ **options: Options (unused for FastEmbed)
+
+ Returns:
+ np.ndarray: Embedding vector from FastEmbed model
+ """
+ embeddings = list(self.fastembed_model.embed([text]))
+ if embeddings:
+ embedding = np.array(embeddings[0], dtype=np.float32)
+ # Normalize if requested
+ if self.normalize:
+ norm = np.linalg.norm(embedding)
+ if norm > 0:
+ embedding = embedding / norm
+ return embedding
+ else:
+ raise ProcessingError("FastEmbed returned empty embedding")
+
def _embed_fallback(self, text: str, **options) -> np.ndarray:
"""
Fallback embedding using hash-based method.
@@ -280,7 +349,17 @@ class TextEmbedder:
self.logger.debug(f"Generating embeddings for {len(texts)} text(s)")
- if self.model:
+ if self.fastembed_model:
+ # Use FastEmbed's efficient batch encoding
+ embeddings = list(self.fastembed_model.embed(texts))
+ embeddings_array = np.array(embeddings, dtype=np.float32)
+ # Normalize if requested
+ if self.normalize:
+ norms = np.linalg.norm(embeddings_array, axis=1, keepdims=True)
+ norms[norms == 0] = 1 # Avoid division by zero
+ embeddings_array = embeddings_array / norms
+ return embeddings_array
+ elif self.model:
# Use model's efficient batch encoding
embeddings = self.model.encode(
texts, normalize_embeddings=self.normalize, **options
@@ -349,7 +428,8 @@ class TextEmbedder:
Returns:
int: Embedding dimension (number of features in embedding vector).
- - Model-based: Dimension from loaded model (typically 384-768)
+ - FastEmbed: Dimension from loaded model (typically 384-768)
+ - Sentence-transformers: Dimension from loaded model (typically 384-768)
- Fallback: 128 (hash-based embedding dimension)
Example:
@@ -357,7 +437,74 @@ class TextEmbedder:
>>> dim = embedder.get_embedding_dimension()
>>> print(f"Embedding dimension: {dim}")
"""
- if self.model:
+ if self.fastembed_model:
+ # FastEmbed doesn't expose dimension directly, so we generate a test embedding
+ try:
+ test_emb = self._embed_with_fastembed("test")
+ return len(test_emb)
+ except Exception:
+ # Default FastEmbed dimension
+ return 384
+ elif self.model:
return self.model.get_sentence_embedding_dimension()
else:
return 128 # Fallback hash-based embedding dimension
+
+ def get_method(self) -> str:
+ """
+ Get the active embedding method being used.
+
+ Returns:
+ str: Active method name - "fastembed", "sentence_transformers", or "fallback"
+
+ Example:
+ >>> embedder = TextEmbedder(method="fastembed")
+ >>> method = embedder.get_method()
+ >>> print(f"Using method: {method}")
+ """
+ if self.fastembed_model:
+ return "fastembed"
+ elif self.model:
+ return "sentence_transformers"
+ else:
+ return "fallback"
+
+ def get_model_info(self) -> Dict[str, Any]:
+ """
+ Get detailed information about the active embedding model.
+
+ Returns:
+ dict: Dictionary containing:
+ - method: Active embedding method ("fastembed", "sentence_transformers", "fallback")
+ - model_name: Model name being used
+ - model_loaded: Whether the model is successfully loaded
+ - dimension: Embedding dimension
+ - device: Device being used (for sentence-transformers)
+ - normalize: Whether embeddings are normalized
+
+ Example:
+ >>> embedder = TextEmbedder(method="fastembed", model_name="BAAI/bge-small-en-v1.5")
+ >>> info = embedder.get_model_info()
+ >>> print(f"Method: {info['method']}")
+ >>> print(f"Model: {info['model_name']}")
+ >>> print(f"Dimension: {info['dimension']}")
+ """
+ method = self.get_method()
+ model_loaded = (
+ self.fastembed_model is not None
+ if method == "fastembed"
+ else (self.model is not None if method == "sentence_transformers" else False)
+ )
+
+ info = {
+ "method": method,
+ "model_name": self.model_name,
+ "model_loaded": model_loaded,
+ "dimension": self.get_embedding_dimension(),
+ "normalize": self.normalize,
+ }
+
+ if method == "sentence_transformers":
+ info["device"] = self.device
+
+ return info
diff --git a/semantica/embeddings/vector_embedding_manager.py b/semantica/embeddings/vector_embedding_manager.py
new file mode 100644
index 00000000..8daa5bc3
--- /dev/null
+++ b/semantica/embeddings/vector_embedding_manager.py
@@ -0,0 +1,383 @@
+"""
+Vector Embedding Manager Module
+
+This module provides utilities for managing embeddings specifically for vector databases,
+including formatting, validation, and integration helpers for various vector DB backends.
+
+Key Features:
+ - Format embeddings for vector DB storage
+ - Validate embedding dimensions for different backends
+ - Normalize embeddings for vector DB requirements
+ - Create metadata compatible with vector DBs
+ - Integration helpers for FAISS, Pinecone, Weaviate, Qdrant, Milvus
+
+Example Usage:
+ >>> from semantica.embeddings import VectorEmbeddingManager
+ >>> manager = VectorEmbeddingManager()
+ >>> formatted = manager.prepare_for_vector_db(embeddings, metadata, backend="faiss")
+"""
+
+from typing import Any, Dict, List, Optional, Union
+
+import numpy as np
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .embedding_generator import EmbeddingGenerator
+
+
+class VectorEmbeddingManager:
+ """
+ Manager for embeddings in vector database contexts.
+
+ This class provides utilities for preparing, validating, and formatting
+ embeddings specifically for vector database storage and retrieval.
+ Supports multiple vector DB backends with backend-specific optimizations.
+
+ Supported Backends:
+ - FAISS: Local vector storage
+ - Pinecone: Cloud vector database
+ - Weaviate: GraphQL-based vector database
+ - Qdrant: Vector similarity search engine
+ - Milvus: Open-source vector database
+
+ Example Usage:
+ >>> manager = VectorEmbeddingManager()
+ >>> # Prepare embeddings for FAISS
+ >>> formatted = manager.prepare_for_vector_db(
+ ... embeddings,
+ ... metadata=metadata_list,
+ ... backend="faiss"
+ ... )
+ >>> # Validate dimensions
+ >>> is_valid = manager.validate_dimensions(embeddings, backend="pinecone")
+ """
+
+ def __init__(self, embedding_generator: Optional[EmbeddingGenerator] = None):
+ """
+ Initialize vector embedding manager.
+
+ Args:
+ embedding_generator: Optional EmbeddingGenerator instance for
+ generating embeddings if needed
+ """
+ self.logger = get_logger("vector_embedding_manager")
+ self.embedding_generator = embedding_generator or EmbeddingGenerator()
+
+ # Backend-specific dimension requirements
+ self.backend_requirements = {
+ "faiss": {"min_dim": 1, "max_dim": None, "dtype": np.float32},
+ "pinecone": {"min_dim": 1, "max_dim": 20000, "dtype": np.float32},
+ "weaviate": {"min_dim": 1, "max_dim": None, "dtype": np.float32},
+ "qdrant": {"min_dim": 1, "max_dim": None, "dtype": np.float32},
+ "milvus": {"min_dim": 1, "max_dim": 32768, "dtype": np.float32},
+ }
+
+ def prepare_for_vector_db(
+ self,
+ embeddings: np.ndarray,
+ metadata: Optional[List[Dict[str, Any]]] = None,
+ backend: str = "faiss",
+ normalize: bool = True,
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Prepare embeddings and metadata for vector database storage.
+
+ Formats embeddings and metadata according to backend-specific requirements.
+ Validates dimensions, normalizes if needed, and creates compatible data structures.
+
+ Args:
+ embeddings: Embeddings array (n_samples, embedding_dim) or (embedding_dim,)
+ metadata: Optional list of metadata dictionaries (one per embedding)
+ backend: Vector DB backend ("faiss", "pinecone", "weaviate", "qdrant", "milvus")
+ normalize: Whether to normalize embeddings (default: True)
+ **options: Additional backend-specific options
+
+ Returns:
+ Dictionary containing:
+ - vectors: Formatted embeddings array
+ - metadata: Formatted metadata (if provided)
+ - ids: Generated IDs (if not provided in metadata)
+ - backend_info: Backend-specific information
+
+ Raises:
+ ProcessingError: If embeddings are invalid or backend is unsupported
+
+ Example:
+ >>> embeddings = np.random.rand(10, 384).astype(np.float32)
+ >>> metadata = [{"text": f"doc_{i}"} for i in range(10)]
+ >>> result = manager.prepare_for_vector_db(
+ ... embeddings, metadata, backend="pinecone"
+ ... )
+ """
+ if backend.lower() not in self.backend_requirements:
+ raise ProcessingError(
+ f"Unsupported backend: {backend}. "
+ f"Supported: {list(self.backend_requirements.keys())}"
+ )
+
+ # Validate embeddings
+ if not self.validate_dimensions(embeddings, backend):
+ raise ProcessingError(
+ f"Embeddings do not meet requirements for backend: {backend}"
+ )
+
+ # Normalize embeddings if requested
+ if normalize:
+ embeddings = self.normalize_for_storage(embeddings)
+
+ # Ensure correct dtype
+ req = self.backend_requirements[backend.lower()]
+ if embeddings.dtype != req["dtype"]:
+ embeddings = embeddings.astype(req["dtype"])
+
+ # Handle single embedding vs batch
+ if embeddings.ndim == 1:
+ embeddings = embeddings.reshape(1, -1)
+
+ # Prepare metadata
+ formatted_metadata = None
+ if metadata:
+ formatted_metadata = self.create_metadata(
+ metadata, backend=backend, **options
+ )
+
+ # Generate IDs if not provided
+ ids = options.get("ids")
+ if ids is None:
+ ids = [f"vec_{i}" for i in range(len(embeddings))]
+
+ result = {
+ "vectors": embeddings,
+ "metadata": formatted_metadata,
+ "ids": ids,
+ "backend": backend.lower(),
+ "shape": embeddings.shape,
+ "dtype": str(embeddings.dtype),
+ }
+
+ # Add backend-specific information
+ result["backend_info"] = self._get_backend_info(backend, embeddings, **options)
+
+ return result
+
+ def batch_prepare(
+ self,
+ embeddings_list: List[np.ndarray],
+ metadata_list: Optional[List[Dict[str, Any]]] = None,
+ backend: str = "faiss",
+ **options,
+ ) -> Dict[str, Any]:
+ """
+ Prepare multiple embedding batches for vector database storage.
+
+ Args:
+ embeddings_list: List of embedding arrays
+ metadata_list: Optional list of metadata lists (one per embedding batch)
+ backend: Vector DB backend
+ **options: Additional options
+
+ Returns:
+ Dictionary with prepared data for all batches
+ """
+ all_embeddings = []
+ all_metadata = []
+ all_ids = []
+
+ for idx, embeddings in enumerate(embeddings_list):
+ metadata = metadata_list[idx] if metadata_list else None
+ batch_ids = options.get("ids")
+ if batch_ids:
+ batch_ids = batch_ids[idx] if isinstance(batch_ids[0], list) else None
+
+ prepared = self.prepare_for_vector_db(
+ embeddings, metadata, backend, ids=batch_ids, **options
+ )
+
+ all_embeddings.append(prepared["vectors"])
+ if prepared["metadata"]:
+ all_metadata.extend(prepared["metadata"])
+ all_ids.extend(prepared["ids"])
+
+ # Concatenate all embeddings
+ combined_embeddings = np.vstack(all_embeddings)
+
+ return {
+ "vectors": combined_embeddings,
+ "metadata": all_metadata if all_metadata else None,
+ "ids": all_ids,
+ "backend": backend.lower(),
+ "shape": combined_embeddings.shape,
+ "num_batches": len(embeddings_list),
+ }
+
+ def validate_dimensions(
+ self, embeddings: np.ndarray, backend: str
+ ) -> bool:
+ """
+ Validate embedding dimensions for vector database backend.
+
+ Checks if embeddings meet the dimension requirements for the specified backend.
+
+ Args:
+ embeddings: Embeddings array to validate
+ backend: Vector DB backend name
+
+ Returns:
+ bool: True if dimensions are valid, False otherwise
+
+ Example:
+ >>> is_valid = manager.validate_dimensions(embeddings, backend="pinecone")
+ """
+ if backend.lower() not in self.backend_requirements:
+ self.logger.warning(f"Unknown backend: {backend}, skipping validation")
+ return True
+
+ req = self.backend_requirements[backend.lower()]
+
+ # Handle single embedding
+ if embeddings.ndim == 1:
+ dim = len(embeddings)
+ else:
+ dim = embeddings.shape[1]
+
+ # Check dimension constraints
+ if req["min_dim"] is not None and dim < req["min_dim"]:
+ self.logger.error(
+ f"Dimension {dim} below minimum {req['min_dim']} for {backend}"
+ )
+ return False
+
+ if req["max_dim"] is not None and dim > req["max_dim"]:
+ self.logger.error(
+ f"Dimension {dim} above maximum {req['max_dim']} for {backend}"
+ )
+ return False
+
+ return True
+
+ def normalize_for_storage(
+ self, embeddings: np.ndarray, method: str = "l2"
+ ) -> np.ndarray:
+ """
+ Normalize embeddings for vector database storage.
+
+ Normalizes embeddings according to the specified method. L2 normalization
+ is standard for cosine similarity in most vector databases.
+
+ Args:
+ embeddings: Embeddings array to normalize
+ method: Normalization method ("l2" for L2 normalization)
+
+ Returns:
+ np.ndarray: Normalized embeddings
+
+ Example:
+ >>> normalized = manager.normalize_for_storage(embeddings)
+ """
+ if method == "l2":
+ # L2 normalization
+ if embeddings.ndim == 1:
+ norm = np.linalg.norm(embeddings)
+ if norm > 0:
+ return embeddings / norm
+ return embeddings
+ else:
+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)
+ norms[norms == 0] = 1 # Avoid division by zero
+ return embeddings / norms
+ else:
+ self.logger.warning(f"Unknown normalization method: {method}")
+ return embeddings
+
+ def create_metadata(
+ self,
+ metadata: List[Dict[str, Any]],
+ backend: str = "faiss",
+ **options,
+ ) -> List[Dict[str, Any]]:
+ """
+ Create metadata compatible with vector database backend.
+
+ Formats metadata according to backend-specific requirements and constraints.
+
+ Args:
+ metadata: List of metadata dictionaries
+ backend: Vector DB backend
+ **options: Additional formatting options
+
+ Returns:
+ List of formatted metadata dictionaries
+
+ Example:
+ >>> metadata = [{"text": "doc1", "category": "science"}]
+ >>> formatted = manager.create_metadata(metadata, backend="pinecone")
+ """
+ formatted = []
+
+ for meta in metadata:
+ # Create a copy to avoid modifying original
+ formatted_meta = meta.copy()
+
+ # Backend-specific formatting
+ if backend.lower() == "pinecone":
+ # Pinecone has specific metadata requirements
+ # Remove None values and ensure types are compatible
+ formatted_meta = {
+ k: v
+ for k, v in formatted_meta.items()
+ if v is not None
+ and isinstance(v, (str, int, float, bool, list))
+ }
+ elif backend.lower() == "weaviate":
+ # Weaviate uses specific property types
+ # Ensure values are compatible
+ formatted_meta = {
+ k: v
+ for k, v in formatted_meta.items()
+ if v is not None
+ }
+ elif backend.lower() == "qdrant":
+ # Qdrant supports various payload types
+ formatted_meta = {
+ k: v
+ for k, v in formatted_meta.items()
+ if v is not None
+ }
+
+ formatted.append(formatted_meta)
+
+ return formatted
+
+ def _get_backend_info(
+ self, backend: str, embeddings: np.ndarray, **options
+ ) -> Dict[str, Any]:
+ """
+ Get backend-specific information for embeddings.
+
+ Args:
+ backend: Vector DB backend name
+ embeddings: Embeddings array
+ **options: Additional options
+
+ Returns:
+ Dictionary with backend-specific information
+ """
+ info = {
+ "backend": backend.lower(),
+ "num_vectors": len(embeddings),
+ "dimension": embeddings.shape[1] if embeddings.ndim > 1 else len(embeddings),
+ "dtype": str(embeddings.dtype),
+ }
+
+ # Add backend-specific details
+ if backend.lower() == "faiss":
+ info["index_type"] = options.get("index_type", "flat")
+ elif backend.lower() == "pinecone":
+ info["namespace"] = options.get("namespace", "default")
+ elif backend.lower() == "weaviate":
+ info["class_name"] = options.get("class_name", "Document")
+
+ return info
+