Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(embeddings): enhance documentation and code quality for embeddings module

KaifAhmad158315d6d7560
diff --git a/semantica/embeddings/__init__.py b/semantica/embeddings/__init__.py
index c5327aa8..d14e76a1 100644
--- a/semantica/embeddings/__init__.py
+++ b/semantica/embeddings/__init__.py
@@ -12,8 +12,13 @@ Exports:
- EmbeddingOptimizer: Embedding optimization and fine-tuning
- ContextManager: Embedding context management
- ProviderAdapters: Provider-specific adapters
+ - build: Module-level build function for embedding generation
"""
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+import numpy as np
+
from .embedding_generator import EmbeddingGenerator
from .text_embedder import TextEmbedder
from .image_embedder import ImageEmbedder
@@ -61,4 +66,91 @@ __all__ = [
"AttentionPooling",
"HierarchicalPooling",
"PoolingStrategyFactory",
+ "build",
]
+
+
+def build(
+ data: Union[str, Path, List[Union[str, Path]]],
+ data_type: Optional[str] = None,
+ model: Optional[str] = None,
+ batch_size: int = 32,
+ **options
+) -> Dict[str, Any]:
+ """
+ Generate embeddings from data (module-level convenience function).
+
+ This is a user-friendly wrapper around EmbeddingGenerator.generate_embeddings()
+ that creates an EmbeddingGenerator instance and generates embeddings.
+
+ Args:
+ data: Input data - can be text string, file path, or list of texts/paths
+ data_type: Data type - "text", "image", "audio" (auto-detected if None)
+ model: Embedding model to use (default: None, uses default model)
+ batch_size: Batch size for processing multiple items (default: 32)
+ **options: Additional generation options
+
+ Returns:
+ Dictionary containing:
+ - embeddings: Generated embeddings (numpy array or list of arrays)
+ - metadata: Embedding metadata
+ - statistics: Generation statistics
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.embeddings.build(
+ ... data=["text1", "text2", "text3"],
+ ... data_type="text",
+ ... model="sentence-transformers"
+ ... )
+ >>> print(f"Generated {len(result['embeddings'])} embeddings")
+ """
+ # Create EmbeddingGenerator instance
+ config = {}
+ if model:
+ config["model"] = model
+ config.update(options)
+
+ generator = EmbeddingGenerator(config=config, **options)
+
+ # Normalize data to list if single item
+ is_single = not isinstance(data, list)
+ if is_single:
+ data = [data]
+
+ # Generate embeddings
+ if len(data) == 1:
+ # Single item
+ embeddings = generator.generate_embeddings(data[0], data_type=data_type, **options)
+ if is_single:
+ # Return single embedding array
+ return {
+ "embeddings": embeddings,
+ "metadata": {
+ "data_type": data_type or generator._detect_data_type(data[0]),
+ "model": model or "default",
+ "shape": embeddings.shape if isinstance(embeddings, np.ndarray) else None
+ },
+ "statistics": {
+ "total_items": 1,
+ "successful": 1,
+ "failed": 0
+ }
+ }
+ else:
+ # Batch processing
+ results = generator.process_batch(data, **options)
+ return {
+ "embeddings": results["embeddings"],
+ "metadata": {
+ "data_type": data_type or "auto-detected",
+ "model": model or "default",
+ "batch_size": batch_size
+ },
+ "statistics": {
+ "total_items": results["total"],
+ "successful": results["success_count"],
+ "failed": results["failure_count"]
+ },
+ "failed_items": results.get("failed", [])
+ }
diff --git a/semantica/embeddings/audio_embedder.py b/semantica/embeddings/audio_embedder.py
index c79fb9fe..a6c0317b 100644
--- a/semantica/embeddings/audio_embedder.py
+++ b/semantica/embeddings/audio_embedder.py
@@ -1,8 +1,24 @@
"""
-Audio embedder for Semantica framework.
+Audio Embedder Module
-This module provides audio embedding generation for
-speech and audio content analysis.
+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
@@ -21,82 +37,173 @@ except ImportError:
class AudioEmbedder:
- """Audio embedding generator."""
+ """
+ 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.)
- def __init__(self, **config):
+ 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:
- **config: Configuration options:
- - sample_rate: Audio sample rate (default: 16000)
- - normalize: Normalize embeddings (default: True)
+ 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
- self.sample_rate = config.get("sample_rate", 16000)
- self.normalize = config.get("normalize", True)
+ # Audio processing configuration
+ self.sample_rate = sample_rate
+ self.normalize = normalize
+
+ 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 audio.
+ 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
- **options: Embedding options
-
+ audio_path: Path to audio file. Supports common formats (WAV, MP3, etc.)
+ **options: Additional embedding options (currently unused)
+
Returns:
- np.ndarray: Audio embedding vector
+ 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}")
"""
audio_path = Path(audio_path)
+ # Validate audio file exists
if not audio_path.exists():
- raise ValidationError(f"Audio 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():
+ 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:
return self._embed_with_librosa(audio_path, **options)
else:
return self._embed_fallback(audio_path, **options)
def _embed_with_librosa(self, audio_path: Path, **options) -> np.ndarray:
- """Embed audio using librosa."""
+ """
+ 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
+ # Load audio file at specified sample rate
y, sr = librosa.load(str(audio_path), sr=self.sample_rate)
- # Extract features
- # Mel-frequency cepstral coefficients (MFCCs)
+ 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
+ # Chroma features - 12 coefficients
chroma = librosa.feature.chroma_stft(y=y, sr=sr)
- # Spectral contrast
+ # Spectral contrast - 7 coefficients
contrast = librosa.feature.spectral_contrast(y=y, sr=sr)
- # Tonnetz
+ # Tonnetz (tonal centroid) - 6 coefficients
tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
- # Aggregate features (mean across time)
+ # 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),
- np.mean(chroma, axis=1),
- np.mean(contrast, axis=1),
- np.mean(tonnetz, axis=1)
- ])
+ 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
+ # 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:
- self.logger.error(f"Failed to embed audio with librosa: {e}")
- raise ProcessingError(f"Failed to embed audio: {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."""
@@ -141,25 +248,55 @@ class AudioEmbedder:
return np.array(embeddings)
- def extract_features(self, audio_path: Union[str, Path], **options) -> Dict[str, np.ndarray]:
+ def extract_features(
+ self,
+ audio_path: Union[str, Path],
+ **options
+ ) -> Dict[str, Union[np.ndarray, float]]:
"""
- Extract audio features.
+ 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
-
+ **options: Feature extraction options (currently unused)
+
Returns:
- dict: Dictionary of audio features
+ 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),
@@ -169,6 +306,11 @@ class AudioEmbedder:
"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:
diff --git a/semantica/embeddings/context_manager.py b/semantica/embeddings/context_manager.py
index 9171cd18..9d90e1b7 100644
--- a/semantica/embeddings/context_manager.py
+++ b/semantica/embeddings/context_manager.py
@@ -1,8 +1,24 @@
"""
-Context manager for Semantica framework.
+Context Manager Module
-This module provides context window management for
-embedding generation and processing.
+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
@@ -14,7 +30,29 @@ from ..utils.logging import get_logger
@dataclass
class ContextWindow:
- """Context window representation."""
+ """
+ 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
@@ -24,45 +62,100 @@ class ContextWindow:
class ContextManager:
- """Context window manager for embeddings."""
+ """
+ Context window manager for embedding generation and text processing.
- def __init__(self, **config):
+ 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:
- **config: Configuration options:
- - window_size: Context window size in tokens/characters
- - overlap: Overlap between windows
- - max_contexts: Maximum number of contexts to keep
+ 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
- self.window_size = config.get("window_size", 512)
- self.overlap = config.get("overlap", 50)
- self.max_contexts = config.get("max_contexts", 100)
+ # Window configuration
+ self.window_size = window_size
+ self.overlap = overlap
+ self.max_contexts = max_contexts
- # Store contexts
+ # Store contexts (context_id -> ContextWindow)
self.contexts: Dict[str, ContextWindow] = {}
+
+ 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:
+ 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
- start_index: Start index in original text
- **metadata: Context metadata
-
+ 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
+ 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,
@@ -71,108 +164,220 @@ class ContextManager:
metadata=metadata
)
- # Store context
+ # Manage context storage (remove oldest if limit reached)
if len(self.contexts) >= self.max_contexts:
- # Remove oldest context
- oldest_id = min(self.contexts.keys(), key=lambda k: self.contexts[k].start_index)
+ # 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, **options) -> List[ContextWindow]:
+ 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
- **options: Splitting options:
- - preserve_sentences: Preserve sentence boundaries
-
+ 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: List of context windows
+ 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")
"""
+ if not text:
+ self.logger.debug("Empty text provided, returning empty window list")
+ return []
+
windows = []
text_length = len(text)
start = 0
- preserve_sentences = options.get("preserve_sentences", True)
+ 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}"
+ )
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:
- # Try to find sentence boundary
+ # Look for sentence boundaries (., !, ?, newline)
for boundary in ['.', '!', '?', '\n']:
last_boundary = text.rfind(boundary, start, end)
- if last_boundary > start + self.window_size * 0.5: # At least 50% of window
+ # 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 with overlap
+ # 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)"
+ )
+
return windows
def get_context(self, context_id: str) -> Optional[ContextWindow]:
"""
- Get context by ID.
+ Get context window by ID.
+
+ Retrieves a previously created context window using its unique identifier.
Args:
- context_id: Context ID
-
+ context_id: Unique context window identifier
+
Returns:
- ContextWindow: Context window or None
+ ContextWindow if found, None otherwise
+
+ Example:
+ >>> window = manager.get_context("uuid-123")
+ >>> if window:
+ ... print(window.text)
"""
- return self.contexts.get(context_id)
+ 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]:
+ def merge_contexts(
+ self,
+ context_ids: List[str],
+ **options
+ ) -> Optional[ContextWindow]:
"""
- Merge multiple contexts.
+ 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
- **options: Merge options
-
+ context_ids: List of context IDs to merge
+ **options: Additional options passed to create_context_window()
+
Returns:
- ContextWindow: Merged context window
+ 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)}")
"""
- contexts = [self.contexts.get(cid) for cid in context_ids if cid in self.contexts]
+ # 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 by start index
+ # Sort contexts by start index to maintain order
contexts.sort(key=lambda c: c.start_index)
- # Merge texts
+ # 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
+ # 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=True,
- source_contexts=context_ids,
- **merged_metadata
+ **merged_metadata,
+ **options
)
- def clear_contexts(self):
- """Clear all stored contexts."""
+ 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."""
+ """
+ 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 f4994597..7d1def6b 100644
--- a/semantica/embeddings/embedding_generator.py
+++ b/semantica/embeddings/embedding_generator.py
@@ -1,20 +1,27 @@
"""
Embedding Generation Module
-Handles generation of embeddings for text and other data types.
+This module provides comprehensive embedding generation capabilities for text,
+images, audio, and multi-modal content, with support for multiple embedding
+models and optimization strategies.
Key Features:
- - Text embedding generation
+ - Text embedding generation (multiple models: sentence-transformers, OpenAI, BGE, etc.)
+ - Image embedding generation
+ - Audio embedding generation
- Multi-modal embedding support
- - Embedding optimization and fine-tuning
- - Batch embedding processing
- - Embedding quality assessment
+ - Batch processing for efficiency
+ - Embedding optimization and compression
+ - Similarity comparison utilities
-Main Classes:
- - EmbeddingGenerator: Main embedding generation class
- - TextEmbedder: Text-specific embedding generator
- - MultiModalEmbedder: Multi-modal embedding support
- - EmbeddingOptimizer: Embedding optimization engine
+Example Usage:
+ >>> from semantica.embeddings import EmbeddingGenerator
+ >>> generator = EmbeddingGenerator()
+ >>> embeddings = generator.generate_embeddings("Hello world", data_type="text")
+ >>> similarity = generator.compare_embeddings(emb1, emb2, method="cosine")
+
+Author: Semantica Contributors
+License: MIT
"""
from pathlib import Path
@@ -33,48 +40,110 @@ from .embedding_optimizer import EmbeddingOptimizer
class EmbeddingGenerator:
"""
- Embedding generation handler.
+ 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.
+
+ Supported Models:
+ - sentence-transformers: High-quality sentence embeddings
+ - openai: OpenAI text-embedding models
+ - bge: BAAI General Embedding models
+ - clip: CLIP for image-text embeddings
- • Generates embeddings for text and data
- • Supports multiple embedding models
- • Handles batch embedding processing
- • Optimizes embedding quality
- • Manages embedding metadata
- • Supports various embedding formats
+ Example Usage:
+ >>> generator = EmbeddingGenerator()
+ >>> # Single text embedding
+ >>> emb = generator.generate_embeddings("Hello world", data_type="text")
+ >>> # Batch processing
+ >>> embs = generator.process_batch(["text1", "text2", "text3"])
"""
- def __init__(self, config=None, **kwargs):
- """Initialize embedding generator."""
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize embedding generator.
+
+ Sets up embedders for different data types and the embedding optimizer.
+ 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")
+
+ # Merge configuration
self.config = config or {}
self.config.update(kwargs)
- # Initialize embedders
- self.text_embedder = TextEmbedder(**self.config.get("text", {}))
- self.image_embedder = ImageEmbedder(**self.config.get("image", {}))
- self.audio_embedder = AudioEmbedder(**self.config.get("audio", {}))
- self.multimodal_embedder = MultimodalEmbedder(**self.config.get("multimodal", {}))
- self.embedding_optimizer = EmbeddingOptimizer(**self.config.get("optimizer", {}))
+ # 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", {})
- # Supported models
+ 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.logger.info("Embedding generator initialized")
- def generate_embeddings(self, data: Union[str, Path, List], data_type: Optional[str] = None, **options) -> np.ndarray:
+ def generate_embeddings(
+ self,
+ data: Union[str, Path, List[Union[str, Path]]],
+ data_type: Optional[str] = None,
+ **options
+ ) -> np.ndarray:
"""
- Generate embeddings for data.
+ Generate embeddings for input data.
+
+ This method automatically detects the data type if not specified and
+ routes to the appropriate embedder. Supports both single items and batches.
Args:
- data: Input data (text, file path, or list)
- data_type: Data type ("text", "image", "audio", auto-detected if None)
- **options: Generation options
+ 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
+ **options: Additional generation options passed to embedder
Returns:
np.ndarray: Generated embeddings
+ - For single input: 1D array
+ - For batch input: 2D array (batch_size, embedding_dim)
+
+ Raises:
+ ProcessingError: If data type is unsupported or embedding fails
+
+ Example:
+ >>> # Single text
+ >>> 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
+ # Auto-detect data type 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}")
+ # Route to appropriate embedder based on data type
if data_type == "text":
if isinstance(data, str):
return self.text_embedder.embed_text(data, **options)
@@ -91,28 +160,59 @@ class EmbeddingGenerator:
elif isinstance(data, list):
return self.audio_embedder.embed_batch(data, **options)
else:
- raise ProcessingError(f"Unsupported data type: {data_type}")
+ error_msg = (
+ f"Unsupported data type: {data_type}. "
+ f"Supported types: text, image, audio"
+ )
+ raise ProcessingError(error_msg)
def _detect_data_type(self, data: Union[str, Path, List]) -> str:
- """Detect data type from input."""
+ """
+ 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"
- # Check first item
+ # Recursively check first item
return self._detect_data_type(data[0])
- if isinstance(data, Path) or (isinstance(data, str) and Path(data).exists()):
- file_path = Path(data)
+ # 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()
- image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
- audio_extensions = ['.mp3', '.wav', '.flac', '.aac', '.ogg']
+ # 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:
diff --git a/semantica/embeddings/embedding_optimizer.py b/semantica/embeddings/embedding_optimizer.py
index d5c53150..7ececfbb 100644
--- a/semantica/embeddings/embedding_optimizer.py
+++ b/semantica/embeddings/embedding_optimizer.py
@@ -1,8 +1,24 @@
"""
-Embedding optimizer for Semantica framework.
+Embedding Optimizer Module
-This module provides optimization utilities for
-embedding generation and storage.
+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
@@ -21,134 +37,336 @@ except ImportError:
class EmbeddingOptimizer:
- """Embedding optimization utilities."""
+ """
+ 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, **config):
+ 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:
- **config: Configuration options:
- - compression_method: Compression method ("pca", "quantization")
- - target_dimension: Target dimension for reduction
+ 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
- self.compression_method = config.get("compression_method", "pca")
- self.target_dimension = config.get("target_dimension", 128)
+ # Compression configuration
+ self.compression_method = compression_method
+ self.target_dimension = target_dimension
+
+ self.logger.debug(
+ f"Embedding optimizer initialized "
+ f"(method: {compression_method}, target_dim: {target_dimension})"
+ )
- def compress(self, embeddings: np.ndarray, **options) -> np.ndarray:
+ def compress(
+ self,
+ embeddings: np.ndarray,
+ target_dim: Optional[int] = None,
+ method: Optional[str] = None,
+ **options
+ ) -> np.ndarray:
"""
- Compress embeddings.
+ 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 (n_embeddings, dim)
- **options: Compression options:
- - target_dim: Target dimension
- - method: Compression method
-
+ 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
+ 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)
"""
- target_dim = options.get("target_dim", self.target_dimension)
- method = options.get("method", self.compression_method)
+ 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":
return self._compress_pca(embeddings, target_dim)
elif method == "quantization":
return self._compress_quantization(embeddings, **options)
else:
+ self.logger.warning(
+ f"Unknown compression method: {method}. Returning original embeddings."
+ )
return embeddings
def _compress_pca(self, embeddings: np.ndarray, target_dim: int) -> np.ndarray:
- """Compress using PCA."""
+ """
+ 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. Returning original embeddings.")
+ 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:
- self.logger.error(f"Failed to compress with PCA: {e}")
+ error_msg = f"Failed to compress with PCA: {e}"
+ self.logger.error(error_msg)
return embeddings
- def _compress_quantization(self, embeddings: np.ndarray, **options) -> np.ndarray:
- """Compress using quantization."""
- bits = options.get("bits", 8)
+ def _compress_quantization(
+ self,
+ embeddings: np.ndarray,
+ bits: int = 8,
+ **options
+ ) -> np.ndarray:
+ """
+ Compress embeddings using quantization.
- # Quantize to specified bit depth
+ 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) if max_val != min_val else 1
+ scale = (2 ** bits - 1) / (max_val - min_val)
quantized = ((embeddings - min_val) * scale).astype(np.uint8)
- # Dequantize
+ # 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, **options) -> np.ndarray:
+ def reduce_dimensions(
+ self,
+ embeddings: np.ndarray,
+ target_dim: int,
+ method: str = "pca",
+ **options
+ ) -> np.ndarray:
"""
- Reduce embedding dimensions.
+ 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
- target_dim: Target dimension
- **options: Reduction options:
- - method: Reduction method ("pca", "truncate")
-
+ 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
+ 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")
"""
- method = options.get("method", "pca")
+ 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":
- return embeddings[:, :target_dim]
+ # 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], **options) -> np.ndarray:
+ 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 embeddings
- **options: Optimization options
-
+ 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
+ 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)
- # Apply optimizations
- if options.get("normalize", True):
+ 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)
- norms[norms == 0] = 1 # Avoid division by zero
+ # 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]:
+ def profile_performance(
+ self,
+ embeddings: np.ndarray,
+ **options
+ ) -> Dict[str, Any]:
"""
- Profile embedding performance.
+ 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
- **options: Profiling options
-
+ embeddings: Input embeddings array to profile
+ **options: Additional profiling options (unused)
+
Returns:
- dict: Performance metrics
+ 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,
@@ -160,9 +378,15 @@ class EmbeddingOptimizer:
"max": float(np.max(embeddings))
}
- # Sparsity
+ # 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/image_embedder.py b/semantica/embeddings/image_embedder.py
index f2177a83..cae9b27a 100644
--- a/semantica/embeddings/image_embedder.py
+++ b/semantica/embeddings/image_embedder.py
@@ -1,8 +1,24 @@
"""
-Image embedder for Semantica framework.
+Image Embedder Module
-This module provides image embedding generation using
-CLIP and other vision models.
+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
@@ -23,145 +39,331 @@ except ImportError:
class ImageEmbedder:
- """Image embedding generator."""
+ """
+ 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.
- def __init__(self, **config):
+ 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:
- **config: Configuration options:
- - model_name: CLIP model name (default: "ViT-B/32")
- - device: Device ("cpu", "cuda")
- - normalize: Normalize embeddings (default: True)
+ 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
- self.model_name = config.get("model_name", "ViT-B/32")
- self.device = config.get("device", "cpu")
- self.normalize = config.get("normalize", True)
+ # Model configuration
+ self.model_name = model_name
+ self.device = device
+ self.normalize = normalize
- # Initialize model
+ # Initialize model (will be None if CLIP unavailable)
self.model = None
self.preprocess = None
self._initialize_model()
- def _initialize_model(self):
- """Initialize CLIP 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}")
+ 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: {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. Image embedding limited.")
+ 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 image.
+ 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
- **options: Embedding options
-
+ image_path: Path to image file. Supports common formats (JPEG, PNG, etc.)
+ **options: Additional embedding options (currently unused)
+
Returns:
- np.ndarray: Image embedding vector
+ 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}")
"""
image_path = Path(image_path)
+ # Validate image file exists
if not image_path.exists():
- raise ValidationError(f"Image 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():
+ 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:
return self._embed_with_clip(image_path, **options)
else:
return self._embed_fallback(image_path, **options)
def _embed_with_clip(self, image_path: Path, **options) -> np.ndarray:
- """Embed image using CLIP."""
+ """
+ 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:
- self.logger.error(f"Failed to embed image with CLIP: {e}")
- raise ProcessingError(f"Failed to embed image: {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 features."""
- try:
- from PIL import Image
+ """
+ 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)
- # Simple feature extraction
- # Resize to fixed size
+ # 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 and take sample (for simple embedding)
+ # 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:
- embedding = np.pad(flat, (0, 512 - len(flat)), 'constant')[:512]
+ # Pad with zeros if smaller than target dimension
+ embedding = np.pad(
+ flat,
+ (0, 512 - len(flat)),
+ 'constant'
+ )[:512]
- # Normalize
+ # 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:
- self.logger.error(f"Failed to embed image: {e}")
- raise ProcessingError(f"Failed to embed image: {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:
+ def embed_batch(
+ self,
+ image_paths: List[Union[str, Path]],
+ **options
+ ) -> np.ndarray:
"""
- Generate embeddings for multiple images.
+ 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 paths
- **options: Embedding options
-
+ image_paths: List of image file paths. Empty list returns empty array.
+ **options: Additional embedding options passed to embed_image()
+
Returns:
- np.ndarray: Array of embeddings (n_images, embedding_dim)
+ 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:
- embedding = self.embed_image(image_path, **options)
- embeddings.append(embedding)
+ 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 embedding dimension.
+ 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
+ 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 dimension
+ return 512 # Fallback feature-based embedding dimension
diff --git a/semantica/embeddings/multimodal_embedder.py b/semantica/embeddings/multimodal_embedder.py
index 3ac3966a..5e2b3c16 100644
--- a/semantica/embeddings/multimodal_embedder.py
+++ b/semantica/embeddings/multimodal_embedder.py
@@ -1,8 +1,31 @@
"""
-Multimodal embedder for Semantica framework.
+Multimodal Embedder Module
-This module provides cross-modal embedding generation
-for text, image, and audio content.
+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
@@ -18,64 +41,120 @@ from .audio_embedder import AudioEmbedder
class MultimodalEmbedder:
- """Multimodal embedding generator."""
+ """
+ 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, **config):
+ 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:
- **config: Configuration options:
- - align_modalities: Align embeddings across modalities (default: True)
- - normalize: Normalize embeddings (default: True)
+ 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
- self.align_modalities = config.get("align_modalities", True)
- self.normalize = config.get("normalize", True)
+ # Cross-modal configuration
+ self.align_modalities = align_modalities
+ self.normalize = normalize
# Initialize modality-specific embedders
- self.text_embedder = TextEmbedder(**config.get("text", {}))
- self.image_embedder = ImageEmbedder(**config.get("image", {}))
- self.audio_embedder = AudioEmbedder(**config.get("audio", {}))
+ 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)
+
+ 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.
+ Generate embedding for text using text embedder.
+
+ Convenience method that delegates to the text embedder.
Args:
- text: Input text
- **options: Embedding options
-
+ text: Input text string to embed
+ **options: Embedding options passed to text embedder
+
Returns:
- np.ndarray: Text embedding
+ 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.
+ 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
-
+ **options: Embedding options passed to image embedder
+
Returns:
- np.ndarray: Image embedding
+ 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.
+ 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
-
+ **options: Embedding options passed to audio embedder
+
Returns:
- np.ndarray: Audio embedding
+ np.ndarray: Audio embedding vector
"""
return self.audio_embedder.embed_audio(audio_path, **options)
@@ -84,52 +163,103 @@ class MultimodalEmbedder:
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 inputs.
+ 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 (optional)
- image_path: Path to image (optional)
- audio_path: Path to audio (optional)
- **options: Embedding options
-
+ 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: Multimodal embedding
+ 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"
+ ... )
"""
embeddings = []
- # Embed each modality
+ # Embed each provided modality
if text:
+ self.logger.debug("Embedding text modality")
text_emb = self.embed_text(text, **options)
embeddings.append(text_emb)
if image_path:
+ self.logger.debug(f"Embedding image modality: {image_path}")
img_emb = self.embed_image(image_path, **options)
embeddings.append(img_emb)
if audio_path:
+ self.logger.debug(f"Embedding audio modality: {audio_path}")
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")
+ raise ProcessingError(
+ "At least one input (text, image, or audio) is required "
+ "for multimodal embedding"
+ )
- # Combine embeddings
+ # If only one modality, return it directly
if len(embeddings) == 1:
+ self.logger.debug("Single modality provided, returning directly")
return embeddings[0]
- # Align dimensions if needed
+ # Align dimensions if needed (ensures all embeddings have same dimension)
if self.align_modalities:
+ self.logger.debug("Aligning embedding dimensions across modalities")
embeddings = self._align_dimensions(embeddings)
- # Concatenate or average
- if options.get("combine_method", "concat") == "concat":
+ # Combine embeddings using specified method
+ if combine_method == "concat":
+ # Concatenate: preserves all information, larger dimension
combined = np.concatenate(embeddings)
- else:
- # Average
+ 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:
@@ -140,22 +270,49 @@ class MultimodalEmbedder:
return combined
def _align_dimensions(self, embeddings: List[np.ndarray]) -> List[np.ndarray]:
- """Align embedding dimensions."""
- # Find target dimension (smallest common dimension or average)
+ """
+ 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 emb in embeddings:
+ 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
+ # 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
+ # Pad: add zeros to reach target dimension
padding = target_dim - emb.shape[0]
- aligned.append(np.pad(emb, (0, padding), 'constant'))
+ 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
@@ -167,52 +324,107 @@ class MultimodalEmbedder:
**options
) -> float:
"""
- Compute similarity between different modalities.
+ 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
- image_path: Path to image
- audio_path: Path to audio
- **options: Similarity options
-
+ 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: Similarity score (0-1)
+ 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("At least two modalities required for similarity")
+ raise ProcessingError(
+ f"At least two modalities required for cross-modal similarity. "
+ f"Provided: {list(embeddings.keys())}"
+ )
- # Compute pairwise similarities
+ # Get list of embeddings for pairwise comparison
emb_list = list(embeddings.values())
- # Align dimensions
+ # Align dimensions for fair comparison
aligned = self._align_dimensions(emb_list)
- # Compute cosine similarity
+ # 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 np.mean(similarities) if similarities else 0.0
+ # 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 embeddings."""
+ """
+ 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
diff --git a/semantica/embeddings/text_embedder.py b/semantica/embeddings/text_embedder.py
index bf4a8bd2..311f2e4d 100644
--- a/semantica/embeddings/text_embedder.py
+++ b/semantica/embeddings/text_embedder.py
@@ -1,8 +1,25 @@
"""
-Text embedder for Semantica framework.
+Text Embedder Module
-This module provides text embedding generation using
-sentence-transformers and other embedding models.
+This module provides comprehensive text embedding generation capabilities for the
+Semantica framework, supporting multiple embedding models including sentence-transformers
+and fallback methods.
+
+Key Features:
+ - Sentence-transformers integration for high-quality embeddings
+ - Batch processing for multiple texts
+ - Sentence-level embedding extraction
+ - Fallback embedding methods when dependencies unavailable
+ - Configurable normalization and device selection
+
+Example Usage:
+ >>> from semantica.embeddings import TextEmbedder
+ >>> embedder = TextEmbedder(model_name="all-MiniLM-L6-v2")
+ >>> embedding = embedder.embed_text("Hello world")
+ >>> batch_embeddings = embedder.embed_batch(["text1", "text2"])
+
+Author: Semantica Contributors
+License: MIT
"""
from typing import Any, Dict, List, Optional, Union
@@ -20,61 +37,142 @@ except ImportError:
class TextEmbedder:
- """Text embedding generator."""
+ """
+ Text embedding generator for semantic text representation.
+
+ This class provides text embedding generation using sentence-transformers
+ models or fallback methods. Supports single text, batch processing, and
+ sentence-level embedding extraction.
+
+ Features:
+ - Sentence-transformers model integration
+ - Batch processing for efficiency
+ - Sentence-level embedding extraction
+ - Fallback hash-based embeddings (when dependencies unavailable)
+ - Configurable normalization and device selection
+
+ Example Usage:
+ >>> embedder = TextEmbedder(
+ ... model_name="all-MiniLM-L6-v2",
+ ... device="cpu",
+ ... normalize=True
+ ... )
+ >>> embedding = embedder.embed_text("Hello world")
+ >>> dim = embedder.get_embedding_dimension()
+ """
- def __init__(self, **config):
+ def __init__(
+ self,
+ model_name: str = "all-MiniLM-L6-v2",
+ device: str = "cpu",
+ normalize: bool = True,
+ **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.
+
Args:
- **config: Configuration options:
- - model_name: Model name (default: "all-MiniLM-L6-v2")
- - device: Device ("cpu", "cuda")
- - normalize: Normalize embeddings (default: True)
+ model_name: Name of sentence-transformers model to use
+ (default: "all-MiniLM-L6-v2")
+ 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("text_embedder")
self.config = config
- self.model_name = config.get("model_name", "all-MiniLM-L6-v2")
- self.device = config.get("device", "cpu")
- self.normalize = config.get("normalize", True)
+ # Model configuration
+ self.model_name = model_name
+ self.device = device
+ self.normalize = normalize
- # Initialize model
+ # Initialize model (will be None if sentence-transformers unavailable)
self.model = None
self._initialize_model()
- def _initialize_model(self):
- """Initialize embedding model."""
+ def _initialize_model(self) -> None:
+ """
+ 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.
+ """
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}")
+ 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}")
+ 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. Using fallback embedding.")
+ 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:
"""
- Generate embedding for text.
+ Generate embedding for a single text string.
+
+ This method creates a semantic embedding vector for the input text using
+ the configured model. Returns a normalized vector suitable for similarity
+ calculations.
Args:
- text: Input text
- **options: Embedding options
-
+ text: Input text string to embed. Must be non-empty.
+ **options: Additional embedding options passed to model:
+ - show_progress_bar: Show progress bar for encoding
+ - convert_to_numpy: Convert to numpy array (default: True)
+ - batch_size: Batch size for processing
+
Returns:
- np.ndarray: Text embedding vector
+ np.ndarray: 1D embedding vector of shape (embedding_dim,).
+ Dimension depends on model (typically 384-768).
+
+ Raises:
+ ProcessingError: If text is empty or embedding generation fails
+
+ Example:
+ >>> embedder = TextEmbedder()
+ >>> embedding = embedder.embed_text("The quick brown fox")
+ >>> print(f"Embedding shape: {embedding.shape}")
+ >>> print(f"Embedding dimension: {len(embedding)}")
"""
- if not text:
- raise ProcessingError("Text cannot be empty")
+ if not text or not text.strip():
+ raise ProcessingError("Text cannot be empty or whitespace-only")
+ # Use model if available, otherwise fallback
if self.model:
return self._embed_with_model(text, **options)
else:
return self._embed_fallback(text, **options)
def _embed_with_model(self, text: str, **options) -> np.ndarray:
- """Embed text using sentence-transformers model."""
+ """
+ Embed text using sentence-transformers model.
+
+ This method uses the loaded sentence-transformers model to generate
+ high-quality semantic embeddings.
+
+ Args:
+ text: Input text to embed
+ **options: Options passed to model.encode()
+
+ Returns:
+ np.ndarray: Embedding vector from model
+ """
embeddings = self.model.encode(
[text],
normalize_embeddings=self.normalize,
@@ -84,17 +182,38 @@ class TextEmbedder:
return embeddings[0]
def _embed_fallback(self, text: str, **options) -> np.ndarray:
- """Fallback embedding using simple hash-based method."""
- # Simple hash-based embedding (for testing without dependencies)
+ """
+ Fallback embedding using hash-based method.
+
+ This method generates a deterministic embedding using SHA-256 hashing
+ when sentence-transformers is not available. Useful for testing or
+ when dependencies cannot be installed.
+
+ Note: Hash-based embeddings are not semantic and should not be used
+ for production similarity calculations. They are deterministic but
+ don't capture semantic meaning.
+
+ Args:
+ text: Input text to embed
+ **options: Unused (for compatibility)
+
+ Returns:
+ np.ndarray: 128-dimensional hash-based embedding vector
+ """
import hashlib
- hash_obj = hashlib.sha256(text.encode())
+ # Generate hash from text
+ hash_obj = hashlib.sha256(text.encode('utf-8'))
hash_bytes = hash_obj.digest()
# Convert to numpy array (128-dimensional)
- embedding = np.frombuffer(hash_bytes + hash_bytes[:64], dtype=np.float32)[:128]
+ # Use hash bytes + first 64 bytes to get 128 bytes total
+ embedding = np.frombuffer(
+ hash_bytes + hash_bytes[:64],
+ dtype=np.float32
+ )[:128]
- # Normalize
+ # Normalize if requested
if self.normalize:
norm = np.linalg.norm(embedding)
if norm > 0:
@@ -104,19 +223,36 @@ class TextEmbedder:
def embed_batch(self, texts: List[str], **options) -> np.ndarray:
"""
- Generate embeddings for multiple texts.
+ Generate embeddings for multiple texts in batch.
+
+ This method efficiently processes multiple texts at once, which is
+ faster than calling embed_text() repeatedly. The model processes
+ texts in batches for optimal performance.
Args:
- texts: List of input texts
- **options: Embedding options
-
+ texts: List of text strings to embed. Empty list returns empty array.
+ **options: Additional embedding options:
+ - batch_size: Batch size for processing (default: model default)
+ - show_progress_bar: Show progress bar (default: False)
+ - convert_to_numpy: Convert to numpy array (default: True)
+
Returns:
- np.ndarray: Array of embeddings (n_texts, embedding_dim)
+ np.ndarray: 2D array of embeddings with shape (n_texts, embedding_dim).
+ Returns empty array if input list is empty.
+
+ Example:
+ >>> texts = ["First text", "Second text", "Third text"]
+ >>> embeddings = embedder.embed_batch(texts)
+ >>> print(f"Shape: {embeddings.shape}") # (3, embedding_dim)
"""
if not texts:
+ self.logger.debug("Empty text list provided, returning empty array")
return np.array([])
+ self.logger.debug(f"Generating embeddings for {len(texts)} text(s)")
+
if self.model:
+ # Use model's efficient batch encoding
embeddings = self.model.encode(
texts,
normalize_embeddings=self.normalize,
@@ -124,37 +260,79 @@ class TextEmbedder:
)
return np.array(embeddings)
else:
- return np.array([self._embed_fallback(text, **options) for text in texts])
+ # Fallback: process each text individually
+ self.logger.debug("Using fallback method for batch embedding")
+ return np.array([
+ self._embed_fallback(text, **options) for text in texts
+ ])
def embed_sentences(self, text: str, **options) -> List[np.ndarray]:
"""
- Generate embeddings for each sentence.
+ Generate embeddings for each sentence in text.
+
+ This method splits the input text into sentences and generates an
+ embedding for each sentence. Useful for document-level analysis where
+ sentence-level embeddings are needed.
+
+ Sentence Splitting:
+ - Splits on sentence boundaries (. ! ?)
+ - Preserves sentence content
+ - Filters out empty sentences
Args:
- text: Input text
- **options: Embedding options
+ text: Input text containing multiple sentences
+ **options: Embedding options passed to embed_batch()
Returns:
- list: List of sentence embeddings
+ List of np.ndarray: One embedding vector per sentence.
+ Returns empty list if no sentences found.
+
+ Example:
+ >>> text = "First sentence. Second sentence! Third sentence?"
+ >>> sentence_embeddings = embedder.embed_sentences(text)
+ >>> print(f"Found {len(sentence_embeddings)} sentence embeddings")
"""
import re
+
+ if not text or not text.strip():
+ self.logger.debug("Empty text provided for sentence embedding")
+ return []
+
+ # Split text into sentences using punctuation
sentences = re.split(r'[.!?]+', text)
+ # Clean and filter sentences
sentences = [s.strip() for s in sentences if s.strip()]
- if sentences:
- embeddings = self.embed_batch(sentences, **options)
- return [embeddings[i] for i in range(len(sentences))]
+ if not sentences:
+ self.logger.debug("No sentences found in text")
+ return []
+
+ self.logger.debug(f"Extracting embeddings for {len(sentences)} sentence(s)")
+
+ # Generate embeddings for all sentences in batch
+ embeddings = self.embed_batch(sentences, **options)
- return []
+ # Convert to list of individual embeddings
+ return [embeddings[i] for i in range(len(sentences))]
def get_embedding_dimension(self) -> int:
"""
- Get embedding dimension.
+ 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
+ int: Embedding dimension (number of features in embedding vector).
+ - Model-based: Dimension from loaded model (typically 384-768)
+ - Fallback: 128 (hash-based embedding dimension)
+
+ Example:
+ >>> embedder = TextEmbedder()
+ >>> dim = embedder.get_embedding_dimension()
+ >>> print(f"Embedding dimension: {dim}")
"""
if self.model:
return self.model.get_sentence_embedding_dimension()
else:
- return 128 # Fallback dimension
+ return 128 # Fallback hash-based embedding dimension