Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Implement split module: semantic_chunker, sliding_window_chunker, structural_chunker, table_chunker, chunk_validator, provenance_tracker

KaifAhmad15eabcf902431
diff --git a/libs/semantica/split/chunk_validator.py b/libs/semantica/split/chunk_validator.py
index 9747e0cf..a8125509 100644
--- a/libs/semantica/split/chunk_validator.py
+++ b/libs/semantica/split/chunk_validator.py
@@ -5,10 +5,255 @@ This module provides quality validation for document chunks
to ensure proper splitting and data integrity.
"""
-# TODO: Implement chunk validation
-# - Chunk quality assessment and scoring
-# - Size and content validation
-# - Semantic coherence checking
-# - Error detection and reporting
-# - Validation rule configuration
-# - Batch validation and reporting
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .semantic_chunker import Chunk
+
+
+@dataclass
+class ValidationResult:
+ """Validation result representation."""
+
+ valid: bool
+ score: float
+ errors: List[str] = field(default_factory=list)
+ warnings: List[str] = field(default_factory=list)
+ metrics: Dict[str, Any] = field(default_factory=dict)
+
+
+class ChunkValidator:
+ """Chunk validator for quality assessment."""
+
+ def __init__(self, **config):
+ """
+ Initialize chunk validator.
+
+ Args:
+ **config: Configuration options:
+ - min_size: Minimum chunk size in characters (default: 10)
+ - max_size: Maximum chunk size in characters (default: 10000)
+ - min_score: Minimum quality score (default: 0.5)
+ """
+ self.logger = get_logger("chunk_validator")
+ self.config = config
+
+ self.min_size = config.get("min_size", 10)
+ self.max_size = config.get("max_size", 10000)
+ self.min_score = config.get("min_score", 0.5)
+
+ def validate(self, chunk: Chunk, **options) -> ValidationResult:
+ """
+ Validate a single chunk.
+
+ Args:
+ chunk: Chunk to validate
+ **options: Validation options
+
+ Returns:
+ ValidationResult: Validation result
+ """
+ errors = []
+ warnings = []
+ metrics = {}
+
+ # Size validation
+ chunk_size = len(chunk.text)
+ metrics["size"] = chunk_size
+
+ if chunk_size < self.min_size:
+ errors.append(f"Chunk too small: {chunk_size} < {self.min_size}")
+
+ if chunk_size > self.max_size:
+ errors.append(f"Chunk too large: {chunk_size} > {self.max_size}")
+
+ # Content validation
+ if not chunk.text.strip():
+ errors.append("Chunk is empty or whitespace only")
+
+ # Coherence validation
+ coherence_score = self._check_coherence(chunk.text)
+ metrics["coherence"] = coherence_score
+
+ if coherence_score < 0.3:
+ warnings.append(f"Low semantic coherence: {coherence_score:.2f}")
+
+ # Structure validation
+ structure_score = self._check_structure(chunk.text)
+ metrics["structure"] = structure_score
+
+ # Calculate overall score
+ score = self._calculate_score(chunk_size, coherence_score, structure_score, errors)
+ metrics["overall_score"] = score
+
+ valid = len(errors) == 0 and score >= self.min_score
+
+ return ValidationResult(
+ valid=valid,
+ score=score,
+ errors=errors,
+ warnings=warnings,
+ metrics=metrics
+ )
+
+ def validate_batch(self, chunks: List[Chunk], **options) -> Dict[str, Any]:
+ """
+ Validate multiple chunks.
+
+ Args:
+ chunks: List of chunks to validate
+ **options: Validation options
+
+ Returns:
+ dict: Batch validation results
+ """
+ results = []
+ valid_count = 0
+ total_score = 0.0
+
+ for chunk in chunks:
+ result = self.validate(chunk, **options)
+ results.append(result)
+
+ if result.valid:
+ valid_count += 1
+ total_score += result.score
+
+ avg_score = total_score / len(chunks) if chunks else 0.0
+
+ return {
+ "total_chunks": len(chunks),
+ "valid_chunks": valid_count,
+ "invalid_chunks": len(chunks) - valid_count,
+ "average_score": avg_score,
+ "results": results,
+ "summary": {
+ "validity_rate": valid_count / len(chunks) if chunks else 0.0,
+ "average_coherence": sum(r.metrics.get("coherence", 0) for r in results) / len(results) if results else 0.0,
+ "average_structure": sum(r.metrics.get("structure", 0) for r in results) / len(results) if results else 0.0
+ }
+ }
+
+ def _check_coherence(self, text: str) -> float:
+ """
+ Check semantic coherence of text.
+
+ Args:
+ text: Text to check
+
+ Returns:
+ float: Coherence score (0-1)
+ """
+ if not text:
+ return 0.0
+
+ score = 1.0
+
+ # Check sentence completeness
+ sentences = text.split('.')
+ incomplete_sentences = sum(1 for s in sentences if s.strip() and not s.strip()[-1] in '.!?')
+ if sentences:
+ completeness = 1.0 - (incomplete_sentences / len(sentences))
+ score *= completeness
+
+ # Check for very short fragments
+ words = text.split()
+ if len(words) < 3:
+ score *= 0.5
+
+ # Check word repetition (high repetition = lower coherence)
+ if len(words) > 10:
+ unique_words = len(set(word.lower() for word in words))
+ diversity = unique_words / len(words)
+ score *= (0.5 + diversity * 0.5)
+
+ return max(0.0, min(1.0, score))
+
+ def _check_structure(self, text: str) -> float:
+ """
+ Check text structure quality.
+
+ Args:
+ text: Text to check
+
+ Returns:
+ float: Structure score (0-1)
+ """
+ if not text:
+ return 0.0
+
+ score = 1.0
+
+ # Check for proper capitalization
+ first_char = text.strip()[0] if text.strip() else ''
+ if first_char and first_char.islower():
+ score *= 0.9
+
+ # Check for balanced punctuation
+ sentences = [s.strip() for s in text.split('.') if s.strip()]
+ if len(sentences) > 1:
+ # More sentences = better structure
+ structure_factor = min(1.0, len(sentences) / 5.0)
+ score *= (0.7 + structure_factor * 0.3)
+
+ # Check for whitespace issues
+ if ' ' in text or '\t\t' in text:
+ score *= 0.9
+
+ return max(0.0, min(1.0, score))
+
+ def _calculate_score(
+ self,
+ size: int,
+ coherence: float,
+ structure: float,
+ errors: List[str]
+ ) -> float:
+ """
+ Calculate overall validation score.
+
+ Args:
+ size: Chunk size
+ coherence: Coherence score
+ structure: Structure score
+ errors: List of errors
+
+ Returns:
+ float: Overall score (0-1)
+ """
+ # Start with base score
+ score = 1.0
+
+ # Apply size penalty
+ if size < self.min_size or size > self.max_size:
+ score *= 0.5
+
+ # Weighted combination of coherence and structure
+ score = score * (0.6 * coherence + 0.4 * structure)
+
+ # Penalize for errors
+ score *= max(0.0, 1.0 - len(errors) * 0.2)
+
+ return max(0.0, min(1.0, score))
+
+ def filter_valid_chunks(self, chunks: List[Chunk], **options) -> List[Chunk]:
+ """
+ Filter chunks to only include valid ones.
+
+ Args:
+ chunks: List of chunks to filter
+ **options: Validation options
+
+ Returns:
+ list: List of valid chunks
+ """
+ valid_chunks = []
+
+ for chunk in chunks:
+ result = self.validate(chunk, **options)
+ if result.valid:
+ valid_chunks.append(chunk)
+
+ return valid_chunks
diff --git a/libs/semantica/split/provenance_tracker.py b/libs/semantica/split/provenance_tracker.py
index d565affd..0bc96115 100644
--- a/libs/semantica/split/provenance_tracker.py
+++ b/libs/semantica/split/provenance_tracker.py
@@ -5,10 +5,267 @@ This module provides source tracking for document chunks
to maintain data lineage and traceability.
"""
-# TODO: Implement provenance tracking
-# - Source document tracking for each chunk
-# - Position and offset information
-# - Metadata preservation and inheritance
-# - Chunk relationship mapping
-# - Audit trail and versioning
-# - Performance optimization for large datasets
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+from uuid import uuid4
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .semantic_chunker import Chunk
+
+
+@dataclass
+class ProvenanceInfo:
+ """Provenance information representation."""
+
+ chunk_id: str
+ source_document: str
+ source_path: Optional[str] = None
+ start_index: int = 0
+ end_index: int = 0
+ parent_chunk_id: Optional[str] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ version: str = "1.0"
+ timestamp: Optional[str] = None
+
+
+class ProvenanceTracker:
+ """Provenance tracker for chunk source tracking."""
+
+ def __init__(self, **config):
+ """
+ Initialize provenance tracker.
+
+ Args:
+ **config: Configuration options:
+ - store_metadata: Store chunk metadata (default: True)
+ - track_versions: Track version history (default: False)
+ """
+ self.logger = get_logger("provenance_tracker")
+ self.config = config
+
+ self.store_metadata = config.get("store_metadata", True)
+ self.track_versions = config.get("track_versions", False)
+
+ # In-memory store (could be replaced with database)
+ self._provenance_store: Dict[str, ProvenanceInfo] = {}
+ self._chunk_registry: Dict[str, str] = {} # chunk_id -> provenance_id
+
+ def track_chunk(
+ self,
+ chunk: Chunk,
+ source_document: str,
+ source_path: Optional[str] = None,
+ parent_chunk_id: Optional[str] = None,
+ **metadata
+ ) -> str:
+ """
+ Track provenance for a chunk.
+
+ Args:
+ chunk: Chunk to track
+ source_document: Source document identifier
+ source_path: Path to source document
+ parent_chunk_id: ID of parent chunk (if chunk was split)
+ **metadata: Additional metadata
+
+ Returns:
+ str: Provenance ID
+ """
+ chunk_id = str(uuid4())
+ provenance_id = str(uuid4())
+
+ provenance_info = ProvenanceInfo(
+ chunk_id=chunk_id,
+ source_document=source_document,
+ source_path=source_path,
+ start_index=chunk.start_index,
+ end_index=chunk.end_index,
+ parent_chunk_id=parent_chunk_id,
+ metadata={
+ **chunk.metadata,
+ **metadata,
+ "chunk_size": len(chunk.text)
+ } if self.store_metadata else {},
+ version="1.0"
+ )
+
+ self._provenance_store[provenance_id] = provenance_info
+ self._chunk_registry[chunk_id] = provenance_id
+
+ return provenance_id
+
+ def track_chunks(
+ self,
+ chunks: List[Chunk],
+ source_document: str,
+ source_path: Optional[str] = None,
+ **metadata
+ ) -> List[str]:
+ """
+ Track provenance for multiple chunks.
+
+ Args:
+ chunks: List of chunks to track
+ source_document: Source document identifier
+ source_path: Path to source document
+ **metadata: Additional metadata
+
+ Returns:
+ list: List of provenance IDs
+ """
+ provenance_ids = []
+ parent_chunk_id = None
+
+ for chunk in chunks:
+ provenance_id = self.track_chunk(
+ chunk,
+ source_document,
+ source_path,
+ parent_chunk_id,
+ **metadata
+ )
+ provenance_ids.append(provenance_id)
+ parent_chunk_id = provenance_id
+
+ return provenance_ids
+
+ def get_provenance(self, chunk_id: str) -> Optional[ProvenanceInfo]:
+ """
+ Get provenance information for a chunk.
+
+ Args:
+ chunk_id: Chunk ID
+
+ Returns:
+ ProvenanceInfo: Provenance information or None
+ """
+ provenance_id = self._chunk_registry.get(chunk_id)
+ if provenance_id:
+ return self._provenance_store.get(provenance_id)
+ return None
+
+ def get_source_chunks(self, source_document: str) -> List[ProvenanceInfo]:
+ """
+ Get all chunks from a source document.
+
+ Args:
+ source_document: Source document identifier
+
+ Returns:
+ list: List of provenance information
+ """
+ return [
+ prov for prov in self._provenance_store.values()
+ if prov.source_document == source_document
+ ]
+
+ def get_chunk_lineage(self, chunk_id: str) -> List[ProvenanceInfo]:
+ """
+ Get lineage (parent chain) for a chunk.
+
+ Args:
+ chunk_id: Chunk ID
+
+ Returns:
+ list: Lineage chain (oldest to newest)
+ """
+ lineage = []
+ current_chunk_id = chunk_id
+
+ while current_chunk_id:
+ provenance = self.get_provenance(current_chunk_id)
+ if not provenance:
+ break
+
+ lineage.insert(0, provenance)
+ current_chunk_id = provenance.parent_chunk_id
+
+ return lineage
+
+ def link_chunks(self, chunk_id1: str, chunk_id2: str, relationship: str = "related") -> bool:
+ """
+ Link two chunks with a relationship.
+
+ Args:
+ chunk_id1: First chunk ID
+ chunk_id2: Second chunk ID
+ relationship: Relationship type
+
+ Returns:
+ bool: True if linked successfully
+ """
+ prov1 = self.get_provenance(chunk_id1)
+ prov2 = self.get_provenance(chunk_id2)
+
+ if not prov1 or not prov2:
+ return False
+
+ # Add relationship to metadata
+ if "relationships" not in prov1.metadata:
+ prov1.metadata["relationships"] = []
+ prov1.metadata["relationships"].append({
+ "chunk_id": chunk_id2,
+ "relationship": relationship
+ })
+
+ return True
+
+ def export_provenance(self, source_document: Optional[str] = None) -> List[Dict[str, Any]]:
+ """
+ Export provenance information.
+
+ Args:
+ source_document: Filter by source document (optional)
+
+ Returns:
+ list: List of provenance dictionaries
+ """
+ if source_document:
+ provenance_list = self.get_source_chunks(source_document)
+ else:
+ provenance_list = list(self._provenance_store.values())
+
+ return [self._provenance_to_dict(prov) for prov in provenance_list]
+
+ def _provenance_to_dict(self, prov: ProvenanceInfo) -> Dict[str, Any]:
+ """Convert ProvenanceInfo to dictionary."""
+ return {
+ "chunk_id": prov.chunk_id,
+ "source_document": prov.source_document,
+ "source_path": prov.source_path,
+ "start_index": prov.start_index,
+ "end_index": prov.end_index,
+ "parent_chunk_id": prov.parent_chunk_id,
+ "metadata": prov.metadata,
+ "version": prov.version,
+ "timestamp": prov.timestamp
+ }
+
+ def clear(self, source_document: Optional[str] = None) -> int:
+ """
+ Clear provenance data.
+
+ Args:
+ source_document: Clear only for specific document (optional)
+
+ Returns:
+ int: Number of entries cleared
+ """
+ if source_document:
+ # Remove only entries for this document
+ to_remove = [
+ prov_id for prov_id, prov in self._provenance_store.items()
+ if prov.source_document == source_document
+ ]
+ for prov_id in to_remove:
+ prov = self._provenance_store.pop(prov_id, None)
+ if prov:
+ self._chunk_registry.pop(prov.chunk_id, None)
+ return len(to_remove)
+ else:
+ # Clear all
+ count = len(self._provenance_store)
+ self._provenance_store.clear()
+ self._chunk_registry.clear()
+ return count
diff --git a/libs/semantica/split/semantic_chunker.py b/libs/semantica/split/semantic_chunker.py
index df5496c1..94431d0a 100644
--- a/libs/semantica/split/semantic_chunker.py
+++ b/libs/semantica/split/semantic_chunker.py
@@ -5,10 +5,265 @@ This module provides meaning-based document splitting
using spaCy and other NLP libraries for optimal semantic boundaries.
"""
-# TODO: Implement semantic chunking
-# - Meaning-based document splitting
-# - Sentence and paragraph boundary detection
-# - Semantic coherence preservation
-# - Context-aware chunk sizing
-# - Multi-language support
-# - Performance optimization with caching
+import re
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional, Tuple
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+
+try:
+ import spacy
+ SPACY_AVAILABLE = True
+except ImportError:
+ SPACY_AVAILABLE = False
+
+
+@dataclass
+class Chunk:
+ """Chunk representation."""
+
+ text: str
+ start_index: int
+ end_index: int
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class SemanticChunker:
+ """Semantic chunker for meaning-based splitting."""
+
+ def __init__(self, **config):
+ """
+ Initialize semantic chunker.
+
+ Args:
+ **config: Configuration options:
+ - model: spaCy model name (default: "en_core_web_sm")
+ - chunk_size: Target chunk size in characters
+ - chunk_overlap: Overlap between chunks
+ - language: Language code
+ """
+ self.logger = get_logger("semantic_chunker")
+ self.config = config
+
+ self.chunk_size = config.get("chunk_size", 1000)
+ self.chunk_overlap = config.get("chunk_overlap", 200)
+ self.language = config.get("language", "en")
+
+ # Initialize spaCy model if available
+ self.nlp = None
+ if SPACY_AVAILABLE:
+ model_name = config.get("model", "en_core_web_sm")
+ try:
+ self.nlp = spacy.load(model_name)
+ except OSError:
+ self.logger.warning(f"spaCy model {model_name} not found. Using fallback chunking.")
+
+ def chunk(self, text: str, **options) -> List[Chunk]:
+ """
+ Split text into semantic chunks.
+
+ Args:
+ text: Input text to chunk
+ **options: Chunking options:
+ - preserve_sentences: Preserve sentence boundaries (default: True)
+ - preserve_paragraphs: Preserve paragraph boundaries (default: True)
+
+ Returns:
+ list: List of chunks
+ """
+ if not text:
+ return []
+
+ # Use spaCy if available
+ if self.nlp:
+ return self._chunk_with_spacy(text, **options)
+ else:
+ return self._chunk_fallback(text, **options)
+
+ def _chunk_with_spacy(self, text: str, **options) -> List[Chunk]:
+ """Chunk text using spaCy."""
+ chunks = []
+
+ # Process text with spaCy
+ doc = self.nlp(text)
+
+ # Split by sentences first
+ sentences = [sent.text for sent in doc.sents]
+
+ current_chunk_text = ""
+ current_start = 0
+ chunk_start = 0
+
+ for sentence in sentences:
+ sentence_text = sentence.strip()
+ if not sentence_text:
+ continue
+
+ # Check if adding this sentence would exceed chunk size
+ potential_chunk = current_chunk_text + " " + sentence_text if current_chunk_text else sentence_text
+
+ if len(potential_chunk) <= self.chunk_size or not current_chunk_text:
+ # Add sentence to current chunk
+ current_chunk_text = potential_chunk
+ current_start += len(sentence_text) + 1
+ else:
+ # Save current chunk and start new one
+ chunk_text = current_chunk_text.strip()
+ if chunk_text:
+ # Find actual start position in original text
+ start_pos = text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "sentence_count": len(re.split(r'[.!?]+', chunk_text)),
+ "token_count": len(self.nlp(chunk_text))
+ }
+ ))
+
+ # Start new chunk with overlap
+ if self.chunk_overlap > 0:
+ # Include last part of previous chunk as overlap
+ overlap_text = current_chunk_text[-self.chunk_overlap:]
+ current_chunk_text = overlap_text + " " + sentence_text
+ chunk_start = text.find(overlap_text[:50], max(0, chunk_start))
+ else:
+ current_chunk_text = sentence_text
+ chunk_start = text.find(sentence_text[:50], max(0, chunk_start))
+ current_start = len(current_chunk_text)
+
+ # Add final chunk
+ if current_chunk_text.strip():
+ start_pos = text.find(current_chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(current_chunk_text.strip()) if start_pos >= 0 else len(text)
+
+ chunks.append(Chunk(
+ text=current_chunk_text.strip(),
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "sentence_count": len(re.split(r'[.!?]+', current_chunk_text)),
+ "token_count": len(self.nlp(current_chunk_text.strip()))
+ }
+ ))
+
+ return chunks
+
+ def _chunk_fallback(self, text: str, **options) -> List[Chunk]:
+ """Fallback chunking without spaCy."""
+ chunks = []
+
+ # Split by paragraphs first
+ paragraphs = text.split('\n\n')
+
+ current_chunk_text = ""
+ chunk_start = 0
+
+ for para in paragraphs:
+ para = para.strip()
+ if not para:
+ continue
+
+ potential_chunk = current_chunk_text + "\n\n" + para if current_chunk_text else para
+
+ if len(potential_chunk) <= self.chunk_size or not current_chunk_text:
+ current_chunk_text = potential_chunk
+ else:
+ # Save current chunk
+ chunk_text = current_chunk_text.strip()
+ if chunk_text:
+ start_pos = text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text) if start_pos >= 0 else chunk_start + len(chunk_text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "paragraph_count": current_chunk_text.count('\n\n') + 1
+ }
+ ))
+
+ # Start new chunk with overlap
+ if self.chunk_overlap > 0:
+ overlap_text = current_chunk_text[-self.chunk_overlap:]
+ current_chunk_text = overlap_text + "\n\n" + para
+ chunk_start = text.find(overlap_text[:50], max(0, chunk_start))
+ else:
+ current_chunk_text = para
+ chunk_start = text.find(para[:50], max(0, chunk_start))
+
+ # Add final chunk
+ if current_chunk_text.strip():
+ start_pos = text.find(current_chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(current_chunk_text.strip()) if start_pos >= 0 else len(text)
+
+ chunks.append(Chunk(
+ text=current_chunk_text.strip(),
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "paragraph_count": current_chunk_text.count('\n\n') + 1
+ }
+ ))
+
+ return chunks
+
+ def chunk_by_sentences(self, text: str, max_sentences: int = 5) -> List[Chunk]:
+ """
+ Chunk text by sentence boundaries.
+
+ Args:
+ text: Input text
+ max_sentences: Maximum sentences per chunk
+
+ Returns:
+ list: List of chunks
+ """
+ # Split sentences using regex
+ sentences = re.split(r'(?<=[.!?])\s+', text)
+
+ chunks = []
+ current_chunk = []
+ chunk_start = 0
+
+ for sentence in sentences:
+ sentence = sentence.strip()
+ if not sentence:
+ continue
+
+ current_chunk.append(sentence)
+
+ if len(current_chunk) >= max_sentences:
+ chunk_text = ' '.join(current_chunk)
+ start_pos = text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text) if start_pos >= 0 else chunk_start + len(chunk_text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={"sentence_count": len(current_chunk)}
+ ))
+
+ chunk_start = end_pos
+ current_chunk = []
+
+ # Add remaining sentences
+ if current_chunk:
+ chunk_text = ' '.join(current_chunk)
+ start_pos = text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text) if start_pos >= 0 else len(text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={"sentence_count": len(current_chunk)}
+ ))
+
+ return chunks
diff --git a/libs/semantica/split/sliding_window_chunker.py b/libs/semantica/split/sliding_window_chunker.py
index eaff171e..1c742996 100644
--- a/libs/semantica/split/sliding_window_chunker.py
+++ b/libs/semantica/split/sliding_window_chunker.py
@@ -5,10 +5,165 @@ This module provides fixed-size chunking with overlap capabilities
for document processing and analysis.
"""
-# TODO: Implement sliding window chunking
-# - Fixed-size chunk creation with configurable overlap
-# - Sliding window algorithm implementation
-# - Overlap management and deduplication
-# - Boundary detection and preservation
-# - Performance optimization for large documents
-# - Memory-efficient streaming processing
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from .semantic_chunker import Chunk
+
+
+class SlidingWindowChunker:
+ """Sliding window chunker with overlap."""
+
+ def __init__(self, **config):
+ """
+ Initialize sliding window chunker.
+
+ Args:
+ **config: Configuration options:
+ - chunk_size: Chunk size in characters
+ - overlap: Overlap size in characters (default: 0)
+ - stride: Stride size (default: chunk_size - overlap)
+ """
+ self.logger = get_logger("sliding_window_chunker")
+ self.config = config
+
+ self.chunk_size = config.get("chunk_size", 1000)
+ self.overlap = config.get("overlap", 0)
+ self.stride = config.get("stride", self.chunk_size - self.overlap)
+
+ if self.chunk_size <= 0:
+ raise ValidationError("chunk_size must be positive")
+ if self.overlap < 0:
+ raise ValidationError("overlap must be non-negative")
+ if self.overlap >= self.chunk_size:
+ raise ValidationError("overlap must be less than chunk_size")
+
+ def chunk(self, text: str, **options) -> List[Chunk]:
+ """
+ Split text using sliding window approach.
+
+ Args:
+ text: Input text to chunk
+ **options: Chunking options:
+ - preserve_boundaries: Try to preserve word/sentence boundaries (default: True)
+
+ Returns:
+ list: List of chunks
+ """
+ if not text:
+ return []
+
+ preserve_boundaries = options.get("preserve_boundaries", True)
+
+ if preserve_boundaries:
+ return self._chunk_with_boundaries(text)
+ else:
+ return self._chunk_fixed_size(text)
+
+ def _chunk_fixed_size(self, text: str) -> List[Chunk]:
+ """Chunk text with fixed-size windows."""
+ chunks = []
+ text_length = len(text)
+
+ start = 0
+ chunk_index = 0
+
+ while start < text_length:
+ end = min(start + self.chunk_size, text_length)
+ chunk_text = text[start:end]
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start,
+ end_index=end,
+ metadata={
+ "chunk_index": chunk_index,
+ "chunk_size": len(chunk_text),
+ "has_overlap": chunk_index > 0
+ }
+ ))
+
+ start += self.stride
+ chunk_index += 1
+
+ return chunks
+
+ def _chunk_with_boundaries(self, text: str) -> List[Chunk]:
+ """Chunk text preserving word/sentence boundaries."""
+ chunks = []
+ text_length = len(text)
+
+ start = 0
+ chunk_index = 0
+
+ while start < text_length:
+ # Determine end position
+ end_pos = min(start + self.chunk_size, text_length)
+
+ # If not at end, try to find a good boundary
+ if end_pos < text_length:
+ # Look for sentence boundary (., !, ?)
+ boundary_chars = ['.', '!', '?', '\n']
+ for boundary in boundary_chars:
+ last_boundary = text.rfind(boundary, start, end_pos)
+ if last_boundary > start + self.chunk_size * 0.5: # At least 50% of target size
+ end_pos = last_boundary + 1
+ break
+
+ # If no sentence boundary, look for word boundary
+ if end_pos == min(start + self.chunk_size, text_length):
+ last_space = text.rfind(' ', start, end_pos)
+ if last_space > start + self.chunk_size * 0.5:
+ end_pos = last_space
+
+ chunk_text = text[start:end_pos].strip()
+
+ if chunk_text:
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start,
+ end_index=end_pos,
+ metadata={
+ "chunk_index": chunk_index,
+ "chunk_size": len(chunk_text),
+ "has_overlap": chunk_index > 0,
+ "boundary_preserved": end_pos < text_length
+ }
+ ))
+
+ # Move to next chunk with stride
+ start += self.stride
+
+ # Ensure we don't go backwards
+ if start <= end_pos - self.overlap:
+ start = end_pos - self.overlap
+
+ chunk_index += 1
+
+ return chunks
+
+ def chunk_with_overlap(self, text: str, overlap_size: Optional[int] = None) -> List[Chunk]:
+ """
+ Chunk text with specified overlap.
+
+ Args:
+ text: Input text
+ overlap_size: Overlap size (uses default if None)
+
+ Returns:
+ list: List of chunks
+ """
+ original_overlap = self.overlap
+ if overlap_size is not None:
+ self.overlap = overlap_size
+ self.stride = self.chunk_size - self.overlap
+
+ chunks = self.chunk(text)
+
+ # Restore original overlap
+ self.overlap = original_overlap
+ self.stride = self.chunk_size - self.overlap
+
+ return chunks
diff --git a/libs/semantica/split/structural_chunker.py b/libs/semantica/split/structural_chunker.py
index 684201ac..f7577dab 100644
--- a/libs/semantica/split/structural_chunker.py
+++ b/libs/semantica/split/structural_chunker.py
@@ -5,10 +5,252 @@ This module provides document-aware splitting based on
document structure and formatting.
"""
-# TODO: Implement structural chunking
-# - Document structure recognition (headings, sections, paragraphs)
-# - Format-aware splitting (tables, lists, code blocks)
-# - Hierarchical chunk organization
-# - Metadata preservation during splitting
-# - Multi-format document support
-# - Structure validation and error handling
+import re
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional, Tuple
+
+from ..utils.exceptions import ProcessingError
+from ..utils.logging import get_logger
+from .semantic_chunker import Chunk
+
+
+@dataclass
+class StructuralElement:
+ """Structural element representation."""
+
+ type: str # heading, paragraph, list, table, code_block
+ text: str
+ level: int = 0
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class StructuralChunker:
+ """Structural chunker for document-aware splitting."""
+
+ def __init__(self, **config):
+ """
+ Initialize structural chunker.
+
+ Args:
+ **config: Configuration options:
+ - respect_headers: Respect heading hierarchy (default: True)
+ - respect_sections: Respect section boundaries (default: True)
+ - max_chunk_size: Maximum chunk size
+ """
+ self.logger = get_logger("structural_chunker")
+ self.config = config
+
+ self.respect_headers = config.get("respect_headers", True)
+ self.respect_sections = config.get("respect_sections", True)
+ self.max_chunk_size = config.get("max_chunk_size", 2000)
+
+ def chunk(self, text: str, **options) -> List[Chunk]:
+ """
+ Split text based on document structure.
+
+ Args:
+ text: Input text to chunk
+ **options: Chunking options
+
+ Returns:
+ list: List of chunks
+ """
+ if not text:
+ return []
+
+ # Extract structural elements
+ elements = self._extract_structure(text)
+
+ # Group elements into chunks
+ chunks = self._group_elements(elements, text)
+
+ return chunks
+
+ def _extract_structure(self, text: str) -> List[StructuralElement]:
+ """Extract structural elements from text."""
+ elements = []
+ lines = text.split('\n')
+
+ i = 0
+ while i < len(lines):
+ line = lines[i].strip()
+
+ if not line:
+ i += 1
+ continue
+
+ # Detect headings (# for markdown, or all caps lines)
+ if line.startswith('#') or self._is_heading(line, lines, i):
+ level = len(re.match(r'^#+', line).group()) if line.startswith('#') else 1
+ elements.append(StructuralElement(
+ type="heading",
+ text=line,
+ level=level,
+ metadata={"line_number": i + 1}
+ ))
+
+ # Detect lists
+ elif re.match(r'^[-*+]\s|^\d+\.\s', line):
+ list_items = [line]
+ j = i + 1
+ while j < len(lines) and (re.match(r'^[-*+]\s|^\d+\.\s', lines[j].strip()) or not lines[j].strip()):
+ if lines[j].strip():
+ list_items.append(lines[j].strip())
+ j += 1
+
+ elements.append(StructuralElement(
+ type="list",
+ text='\n'.join(list_items),
+ level=0,
+ metadata={"item_count": len(list_items), "line_number": i + 1}
+ ))
+ i = j - 1
+
+ # Detect code blocks
+ elif line.startswith('```') or line.startswith(' '):
+ code_lines = [line]
+ j = i + 1
+ if line.startswith('```'):
+ # Find closing ```
+ while j < len(lines) and not lines[j].strip().startswith('```'):
+ code_lines.append(lines[j])
+ j += 1
+ if j < len(lines):
+ code_lines.append(lines[j])
+ j += 1
+ else:
+ # Indented code block
+ while j < len(lines) and (lines[j].startswith(' ') or not lines[j].strip()):
+ code_lines.append(lines[j])
+ j += 1
+
+ elements.append(StructuralElement(
+ type="code_block",
+ text='\n'.join(code_lines),
+ level=0,
+ metadata={"line_number": i + 1}
+ ))
+ i = j - 1
+
+ # Regular paragraph
+ else:
+ para_lines = [line]
+ j = i + 1
+ while j < len(lines) and lines[j].strip() and not self._is_structure_element(lines[j]):
+ para_lines.append(lines[j].strip())
+ j += 1
+
+ paragraph_text = ' '.join(para_lines)
+ if paragraph_text:
+ elements.append(StructuralElement(
+ type="paragraph",
+ text=paragraph_text,
+ level=0,
+ metadata={"line_number": i + 1}
+ ))
+ i = j - 1
+
+ i += 1
+
+ return elements
+
+ def _is_heading(self, line: str, all_lines: List[str], index: int) -> bool:
+ """Check if line is a heading."""
+ # All caps line followed by blank line
+ if line.isupper() and len(line) > 3 and index + 1 < len(all_lines):
+ if not all_lines[index + 1].strip():
+ return True
+
+ # Line ending with colon and short
+ if line.endswith(':') and len(line) < 100:
+ return True
+
+ return False
+
+ def _is_structure_element(self, line: str) -> bool:
+ """Check if line is a structural element."""
+ return (
+ line.startswith('#') or
+ re.match(r'^[-*+]\s|^\d+\.\s', line) or
+ line.startswith('```') or
+ line.startswith(' ')
+ )
+
+ def _group_elements(self, elements: List[StructuralElement], original_text: str) -> List[Chunk]:
+ """Group structural elements into chunks."""
+ chunks = []
+ current_chunk = []
+ current_size = 0
+ chunk_start = 0
+
+ for element in elements:
+ element_size = len(element.text)
+
+ # Check if adding this element would exceed max size
+ if current_size + element_size > self.max_chunk_size and current_chunk:
+ # Create chunk from current elements
+ chunk_text = '\n\n'.join([e.text for e in current_chunk])
+ start_pos = original_text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text) if start_pos >= 0 else chunk_start + len(chunk_text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "element_count": len(current_chunk),
+ "element_types": [e.type for e in current_chunk],
+ "structure_preserved": True
+ }
+ ))
+
+ chunk_start = end_pos
+ current_chunk = []
+ current_size = 0
+
+ # Add element to current chunk
+ current_chunk.append(element)
+ current_size += element_size
+
+ # If we hit a major heading, consider breaking here
+ if self.respect_headers and element.type == "heading" and element.level <= 2 and current_chunk:
+ # Save current chunk (excluding the heading if it's new)
+ if len(current_chunk) > 1:
+ chunk_elements = current_chunk[:-1]
+ chunk_text = '\n\n'.join([e.text for e in chunk_elements])
+ start_pos = original_text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text) if start_pos >= 0 else chunk_start + len(chunk_text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "element_count": len(chunk_elements),
+ "element_types": [e.type for e in chunk_elements],
+ "structure_preserved": True
+ }
+ ))
+
+ chunk_start = end_pos
+ current_chunk = [element]
+ current_size = len(element.text)
+
+ # Add final chunk
+ if current_chunk:
+ chunk_text = '\n\n'.join([e.text for e in current_chunk])
+ start_pos = original_text.find(chunk_text[:50], chunk_start)
+ end_pos = start_pos + len(chunk_text) if start_pos >= 0 else len(original_text)
+
+ chunks.append(Chunk(
+ text=chunk_text,
+ start_index=start_pos if start_pos >= 0 else chunk_start,
+ end_index=end_pos,
+ metadata={
+ "element_count": len(current_chunk),
+ "element_types": [e.type for e in current_chunk],
+ "structure_preserved": True
+ }
+ ))
+
+ return chunks
diff --git a/libs/semantica/split/table_chunker.py b/libs/semantica/split/table_chunker.py
index 63ff849d..29b181e5 100644
--- a/libs/semantica/split/table_chunker.py
+++ b/libs/semantica/split/table_chunker.py
@@ -5,10 +5,211 @@ This module provides specialized chunking for tabular data
while preserving table structure and relationships.
"""
-# TODO: Implement table chunking
-# - Table structure recognition and preservation
-# - Row and column-based chunking strategies
-# - Table metadata and schema extraction
-# - Cross-table relationship handling
-# - Performance optimization for large tables
-# - Export to various table formats
+from dataclasses import dataclass, field
+from typing import Any, Dict, List, Optional, Union
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from .semantic_chunker import Chunk
+
+
+@dataclass
+class TableChunk:
+ """Table chunk representation."""
+
+ rows: List[List[str]]
+ headers: List[str]
+ start_row: int
+ end_row: int
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class TableChunker:
+ """Table-aware chunker for tabular data."""
+
+ def __init__(self, **config):
+ """
+ Initialize table chunker.
+
+ Args:
+ **config: Configuration options:
+ - max_rows: Maximum rows per chunk (default: 100)
+ - preserve_headers: Include headers in each chunk (default: True)
+ - chunk_by_columns: Chunk by columns instead of rows (default: False)
+ """
+ self.logger = get_logger("table_chunker")
+ self.config = config
+
+ self.max_rows = config.get("max_rows", 100)
+ self.preserve_headers = config.get("preserve_headers", True)
+ self.chunk_by_columns = config.get("chunk_by_columns", False)
+
+ def chunk_table(self, table_data: Union[Dict[str, Any], List[List[str]]], **options) -> List[TableChunk]:
+ """
+ Chunk table data.
+
+ Args:
+ table_data: Table data (dict with 'headers' and 'rows' or list of lists)
+ **options: Chunking options
+
+ Returns:
+ list: List of table chunks
+ """
+ # Parse table data
+ if isinstance(table_data, dict):
+ headers = table_data.get("headers", [])
+ rows = table_data.get("rows", [])
+ elif isinstance(table_data, list) and len(table_data) > 0:
+ # First row as headers if not provided
+ if options.get("first_row_as_header", True):
+ headers = table_data[0]
+ rows = table_data[1:]
+ else:
+ headers = [f"Column_{i+1}" for i in range(len(table_data[0]))]
+ rows = table_data
+ else:
+ raise ValidationError("Invalid table data format")
+
+ if self.chunk_by_columns:
+ return self._chunk_by_columns(headers, rows, **options)
+ else:
+ return self._chunk_by_rows(headers, rows, **options)
+
+ def _chunk_by_rows(self, headers: List[str], rows: List[List[str]], **options) -> List[TableChunk]:
+ """Chunk table by rows."""
+ chunks = []
+ max_rows = options.get("max_rows", self.max_rows)
+
+ for i in range(0, len(rows), max_rows):
+ chunk_rows = rows[i:i + max_rows]
+ end_row = min(i + max_rows, len(rows))
+
+ chunks.append(TableChunk(
+ rows=chunk_rows,
+ headers=headers if self.preserve_headers else [],
+ start_row=i,
+ end_row=end_row - 1,
+ metadata={
+ "row_count": len(chunk_rows),
+ "column_count": len(headers),
+ "has_headers": self.preserve_headers
+ }
+ ))
+
+ return chunks
+
+ def _chunk_by_columns(self, headers: List[str], rows: List[List[str]], **options) -> List[TableChunk]:
+ """Chunk table by columns."""
+ chunks = []
+ max_cols = options.get("max_columns", 5)
+
+ for i in range(0, len(headers), max_cols):
+ chunk_headers = headers[i:i + max_cols]
+ chunk_rows = [[row[j] for j in range(i, min(i + max_cols, len(row)))] for row in rows]
+ end_col = min(i + max_cols, len(headers))
+
+ chunks.append(TableChunk(
+ rows=chunk_rows,
+ headers=chunk_headers,
+ start_row=0,
+ end_row=len(rows) - 1,
+ metadata={
+ "row_count": len(chunk_rows),
+ "column_count": len(chunk_headers),
+ "start_column": i,
+ "end_column": end_col - 1,
+ "chunked_by": "columns"
+ }
+ ))
+
+ return chunks
+
+ def chunk_to_text_chunks(self, table_data: Union[Dict[str, Any], List[List[str]]], **options) -> List[Chunk]:
+ """
+ Convert table chunks to text chunks.
+
+ Args:
+ table_data: Table data
+ **options: Chunking options
+
+ Returns:
+ list: List of text chunks
+ """
+ table_chunks = self.chunk_table(table_data, **options)
+ text_chunks = []
+
+ for idx, table_chunk in enumerate(table_chunks):
+ # Convert table to text representation
+ lines = []
+
+ if table_chunk.headers:
+ lines.append(" | ".join(table_chunk.headers))
+ lines.append(" | ".join(["---"] * len(table_chunk.headers)))
+
+ for row in table_chunk.rows:
+ lines.append(" | ".join(str(cell) for cell in row))
+
+ chunk_text = "\n".join(lines)
+
+ text_chunks.append(Chunk(
+ text=chunk_text,
+ start_index=0,
+ end_index=len(chunk_text),
+ metadata={
+ "chunk_type": "table",
+ "chunk_index": idx,
+ "row_count": len(table_chunk.rows),
+ "column_count": len(table_chunk.headers),
+ "start_row": table_chunk.start_row,
+ "end_row": table_chunk.end_row,
+ **table_chunk.metadata
+ }
+ ))
+
+ return text_chunks
+
+ def extract_table_schema(self, table_data: Union[Dict[str, Any], List[List[str]]]) -> Dict[str, Any]:
+ """
+ Extract table schema and metadata.
+
+ Args:
+ table_data: Table data
+
+ Returns:
+ dict: Table schema
+ """
+ if isinstance(table_data, dict):
+ headers = table_data.get("headers", [])
+ rows = table_data.get("rows", [])
+ elif isinstance(table_data, list) and len(table_data) > 0:
+ headers = table_data[0] if table_data else []
+ rows = table_data[1:] if len(table_data) > 1 else []
+ else:
+ return {}
+
+ # Infer column types
+ column_types = {}
+ if rows:
+ for col_idx, header in enumerate(headers):
+ sample_values = [row[col_idx] if col_idx < len(row) else "" for row in rows[:10]]
+
+ # Try to infer type
+ if all(str(v).strip().replace('.', '').replace('-', '').isdigit() for v in sample_values if v):
+ column_types[header] = "numeric"
+ elif all(str(v).lower() in ['true', 'false', 'yes', 'no'] for v in sample_values if v):
+ column_types[header] = "boolean"
+ else:
+ column_types[header] = "text"
+
+ return {
+ "headers": headers,
+ "column_count": len(headers),
+ "row_count": len(rows),
+ "column_types": column_types,
+ "schema": {
+ "columns": [
+ {"name": header, "type": column_types.get(header, "text")}
+ for header in headers
+ ]
+ }
+ }