Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(deduplication): optimize pipeline with blocking strategy, progress tracking, and object compatibility

KaifAhmad19ad1f574af94
diff --git a/semantica/conflicts/conflict_detector.py b/semantica/conflicts/conflict_detector.py
index 2458441f..5443e539 100644
--- a/semantica/conflicts/conflict_detector.py
+++ b/semantica/conflicts/conflict_detector.py
@@ -4,6 +4,7 @@ Conflict Detector
This module provides comprehensive conflict detection capabilities for the
Semantica framework, detecting conflicts from multiple sources and tracking
source disagreements for compliance and investigation.
+Includes integrated progress tracking for large-scale conflict detection.
Algorithms Used:
diff --git a/semantica/conflicts/conflict_resolver.py b/semantica/conflicts/conflict_resolver.py
index 122c7da7..48e26ea4 100644
--- a/semantica/conflicts/conflict_resolver.py
+++ b/semantica/conflicts/conflict_resolver.py
@@ -4,6 +4,7 @@ Conflict Resolver
This module provides comprehensive conflict resolution capabilities for the
Semantica framework, offering multiple strategies for resolving detected conflicts
including voting mechanisms, credibility-based resolution, and expert review.
+The module includes granular progress tracking for large conflict sets.
Algorithms Used:
diff --git a/semantica/deduplication/duplicate_detector.py b/semantica/deduplication/duplicate_detector.py
index 11e6ceec..b3d0ff5c 100644
--- a/semantica/deduplication/duplicate_detector.py
+++ b/semantica/deduplication/duplicate_detector.py
@@ -6,16 +6,16 @@ framework, identifying duplicate entities and relationships in knowledge graphs
similarity thresholds, clustering algorithms, and confidence scoring.
Algorithms Used:
- - Pairwise Comparison: O(n²) all-pairs similarity calculation for complete duplicate detection
+ - Pairwise Comparison: Optimized all-pairs similarity calculation with blocking support
- Batch Processing: Vectorized similarity calculations for efficiency
- Union-Find Algorithm: Disjoint set union (DSU) for duplicate group formation
- Confidence Scoring: Multi-factor confidence calculation combining similarity, name matches, property matches, and type matches
- - Incremental Processing: O(n×m) efficient comparison for new vs existing entities
+ - Incremental Processing: O(n×m) efficient comparison with individual tracking disabled for speed
- Representative Selection: Most complete entity selection from duplicate groups
Key Features:
- Entity duplicate detection using multi-factor similarity metrics
- - Relationship duplicate detection with threshold-based matching
+ - Relationship duplicate detection with granular progress tracking
- Duplicate group formation using union-find algorithm for transitive closure
- Incremental duplicate detection for new entities (streaming scenarios)
- Confidence scoring for duplicate candidates with multiple factors
@@ -419,18 +419,56 @@ class DuplicateDetector:
Returns:
List of duplicate relationship pairs
"""
- duplicates = []
- threshold = options.get("threshold", 0.9)
+ # Track relationship duplicate detection
+ tracking_id = self.progress_tracker.start_tracking(
+ file=None,
+ module="deduplication",
+ submodule="DuplicateDetector",
+ message=f"Detecting duplicate relationships in {len(relationships)} relations",
+ )
- for i in range(len(relationships)):
- for j in range(i + 1, len(relationships)):
- rel1 = relationships[i]
- rel2 = relationships[j]
+ try:
+ duplicates = []
+ threshold = options.get("threshold", 0.9)
+ total_rels = len(relationships)
+ total_pairs = total_rels * (total_rels - 1) // 2
+ processed = 0
+
+ # Update interval
+ if total_pairs <= 10:
+ update_interval = 1
+ else:
+ update_interval = max(1, min(100, total_pairs // 100))
- if self._relationships_are_duplicates(rel1, rel2, threshold):
- duplicates.append((rel1, rel2))
+ for i in range(len(relationships)):
+ for j in range(i + 1, len(relationships)):
+ rel1 = relationships[i]
+ rel2 = relationships[j]
- return duplicates
+ if self._relationships_are_duplicates(rel1, rel2, threshold):
+ duplicates.append((rel1, rel2))
+
+ processed += 1
+ if processed % update_interval == 0 or processed == total_pairs:
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=processed,
+ total=total_pairs,
+ message=f"Checking relationships... {processed}/{total_pairs}"
+ )
+
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Detected {len(duplicates)} duplicate relationships",
+ )
+ return duplicates
+
+ except Exception as e:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
+ raise
def incremental_detect(
self,
@@ -501,9 +539,9 @@ class DuplicateDetector:
# Compare each new entity with all existing entities
for new_entity in new_entities:
for existing_entity in existing_entities:
- # Calculate similarity
+ # Calculate similarity without individual tracking for speed
similarity = self.similarity_calculator.calculate_similarity(
- new_entity, existing_entity
+ new_entity, existing_entity, track=False
)
# Check if above threshold
@@ -553,8 +591,28 @@ class DuplicateDetector:
)
raise
+ def _get_entity_value(self, entity: Any, key: str, default: Any = None) -> Any:
+ """Get value from entity dictionary or object safely."""
+ if hasattr(entity, "__dict__"):
+ # For Entity objects, map 'name' to 'text' and 'type' to 'label'
+ if key == "name":
+ return getattr(entity, "text", default)
+ if key == "type":
+ return getattr(entity, "label", default)
+ if key == "properties":
+ # Check metadata for properties
+ metadata = getattr(entity, "metadata", {})
+ return metadata.get("properties", {})
+ return getattr(entity, key, default)
+ elif isinstance(entity, dict):
+ return entity.get(key, default)
+ return default
+
def _create_duplicate_candidate(
- self, entity1: Dict[str, Any], entity2: Dict[str, Any], similarity_score: float
+ self,
+ entity1: Dict[str, Any],
+ entity2: Dict[str, Any],
+ similarity_score: float,
) -> DuplicateCandidate:
"""
Create duplicate candidate from similarity result.
@@ -563,16 +621,9 @@ class DuplicateDetector:
score and additional factors (name match, property matches, type match)
to calculate a confidence score.
- Confidence Calculation:
- - Base: similarity_score
- - +0.1: Exact name match
- - +0.05 per matching property value
- - +0.05: Same entity type
- - Capped at 1.0
-
Args:
- entity1: First entity dictionary
- entity2: Second entity dictionary
+ entity1: First entity dictionary or object
+ entity2: Second entity dictionary or object
similarity_score: Base similarity score from similarity calculator
Returns:
@@ -582,15 +633,15 @@ class DuplicateDetector:
confidence = similarity_score
# Check for exact name match (strong indicator)
- name1 = entity1.get("name", "").lower().strip()
- name2 = entity2.get("name", "").lower().strip()
+ name1 = str(self._get_entity_value(entity1, "name", "")).lower().strip()
+ name2 = str(self._get_entity_value(entity2, "name", "")).lower().strip()
if name1 == name2 and name1: # Non-empty exact match
reasons.append("exact_name_match")
confidence += 0.1
# Check property value matches
- props1 = entity1.get("properties", {})
- props2 = entity2.get("properties", {})
+ props1 = self._get_entity_value(entity1, "properties", {})
+ props2 = self._get_entity_value(entity2, "properties", {})
common_props = set(props1.keys()) & set(props2.keys())
if common_props:
@@ -604,8 +655,8 @@ class DuplicateDetector:
confidence += 0.05 * prop_matches
# Check entity type match
- entity_type1 = entity1.get("type")
- entity_type2 = entity2.get("type")
+ entity_type1 = self._get_entity_value(entity1, "type")
+ entity_type2 = self._get_entity_value(entity2, "type")
if entity_type1 and entity_type2 and entity_type1 == entity_type2:
reasons.append("same_type")
confidence += 0.05
@@ -635,8 +686,8 @@ class DuplicateDetector:
groups = []
for candidate in candidates:
- entity1_id = candidate.entity1.get("id") or id(candidate.entity1)
- entity2_id = candidate.entity2.get("id") or id(candidate.entity2)
+ entity1_id = self._get_entity_value(candidate.entity1, "id") or id(candidate.entity1)
+ entity2_id = self._get_entity_value(candidate.entity2, "id") or id(candidate.entity2)
group1 = entity_to_group.get(entity1_id)
group2 = entity_to_group.get(entity2_id)
@@ -680,10 +731,11 @@ class DuplicateDetector:
# Update references
for entity in group2.entities:
- entity_id = entity.get("id") or id(entity)
+ entity_id = self._get_entity_value(entity, "id") or id(entity)
entity_to_group[entity_id] = group1
- groups.remove(group2)
+ if group2 in groups:
+ groups.remove(group2)
return groups
@@ -708,8 +760,8 @@ class DuplicateDetector:
# Select entity with most properties/relationships
best_entity = max(
group.entities,
- key=lambda e: len(e.get("properties", {}))
- + len(e.get("relationships", [])),
+ key=lambda e: len(self._get_entity_value(e, "properties", {}))
+ + len(self._get_entity_value(e, "relationships", [])),
)
return best_entity
@@ -719,16 +771,26 @@ class DuplicateDetector:
) -> bool:
"""Check if two relationships are duplicates."""
# Exact match
+ # Handle both dicts and relationship objects if they exist
+ def get_rel_val(rel, key):
+ if hasattr(rel, "__dict__"):
+ return getattr(rel, key, None)
+ if isinstance(rel, dict):
+ return rel.get(key)
+ return None
+
if (
- rel1.get("subject") == rel2.get("subject")
- and rel1.get("predicate") == rel2.get("predicate")
- and rel1.get("object") == rel2.get("object")
+ get_rel_val(rel1, "subject") == get_rel_val(rel2, "subject")
+ and get_rel_val(rel1, "predicate") == get_rel_val(rel2, "predicate")
+ and get_rel_val(rel1, "object") == get_rel_val(rel2, "object")
):
return True
- # Similarity check
+ # Fuzzy match for predicate
+ pred1 = str(get_rel_val(rel1, "predicate") or "")
+ pred2 = str(get_rel_val(rel2, "predicate") or "")
similarity = self.similarity_calculator.calculate_string_similarity(
- str(rel1.get("predicate", "")), str(rel2.get("predicate", ""))
+ pred1, pred2
)
return similarity >= threshold
diff --git a/semantica/deduplication/entity_merger.py b/semantica/deduplication/entity_merger.py
index fd0f9dd0..b19447cd 100644
--- a/semantica/deduplication/entity_merger.py
+++ b/semantica/deduplication/entity_merger.py
@@ -14,7 +14,7 @@ Algorithms Used:
- Merge Quality Validation: Validation of merged entities for completeness and consistency
Key Features:
- - Merge duplicate entities using configurable strategies
+ - Merge duplicate entities using configurable strategies with group-level progress tracking
- Preserve provenance information during merges (tracks merged entity sources)
- Incremental merging of new entities with existing ones
- Conflict resolution for property and relationship merging
@@ -504,9 +504,9 @@ class EntityMerger:
# Record source entities
provenance["merged_from"] = [
{
- "id": e.get("id"),
- "name": e.get("name"),
- "source": e.get("metadata", {}).get("source"),
+ "id": self._get_entity_value(e, "id"),
+ "name": self._get_entity_value(e, "name"),
+ "source": self._get_entity_value(e, "metadata", {}).get("source") if hasattr(e, "metadata") or isinstance(e, dict) else None,
}
for e in source_entities
]
@@ -561,3 +561,20 @@ class EntityMerger:
... print(f"Issues: {validation['issues']}")
"""
return self.merge_strategy_manager.validate_merge(merge_operation.merge_result)
+
+ def _get_entity_value(self, entity: Any, key: str, default: Any = None) -> Any:
+ """Get value from entity dictionary or object safely."""
+ if hasattr(entity, "__dict__"):
+ # For Entity objects, map 'name' to 'text' and 'type' to 'label'
+ if key == "name":
+ return getattr(entity, "text", default)
+ if key == "type":
+ return getattr(entity, "label", default)
+ if key == "properties":
+ # Check metadata for properties
+ metadata = getattr(entity, "metadata", {})
+ return metadata.get("properties", {})
+ return getattr(entity, key, default)
+ elif isinstance(entity, dict):
+ return entity.get(key, default)
+ return default
diff --git a/semantica/deduplication/merge_strategy.py b/semantica/deduplication/merge_strategy.py
index ca26d68f..cc43fc7c 100644
--- a/semantica/deduplication/merge_strategy.py
+++ b/semantica/deduplication/merge_strategy.py
@@ -14,7 +14,7 @@ Algorithms Used:
Key Features:
- Multiple merge strategies (keep_first, keep_most_complete, keep_highest_confidence, etc.)
- - Property-specific merge rules with custom conflict resolution
+ - Property-specific merge rules with granular progress tracking
- Custom conflict resolution functions for complex merging scenarios
- Relationship preservation during merges (union of all relationships)
- Merge quality validation with completeness and consistency checks
@@ -216,6 +216,33 @@ class MergeStrategyManager:
if not entities:
raise ValidationError("No entities to merge")
+ # Pre-process entities to handle both dicts and objects
+ processed_entities = []
+ for entity in entities:
+ if hasattr(entity, "__dict__"):
+ # Map Entity fields to dictionary keys
+ ent_dict = vars(entity).copy()
+ # Add mappings for common fields
+ if "text" in ent_dict and "name" not in ent_dict:
+ ent_dict["name"] = ent_dict["text"]
+ if "label" in ent_dict and "type" not in ent_dict:
+ ent_dict["type"] = ent_dict["label"]
+
+ # Handle metadata properties
+ metadata = ent_dict.get("metadata", {})
+ if "properties" in metadata and "properties" not in ent_dict:
+ ent_dict["properties"] = metadata["properties"]
+ if "relationships" in metadata and "relationships" not in ent_dict:
+ ent_dict["relationships"] = metadata["relationships"]
+
+ processed_entities.append(ent_dict)
+ elif isinstance(entity, dict):
+ processed_entities.append(entity.copy())
+ else:
+ processed_entities.append({"_original": entity})
+
+ entities = processed_entities
+
if len(entities) == 1:
self.progress_tracker.stop_tracking(
tracking_id,
@@ -265,7 +292,7 @@ class MergeStrategyManager:
message=f"Merging properties... ({current_step}/{total_steps}, {total_properties} properties, remaining: {remaining_steps} steps)"
)
merged_properties, property_conflicts = self._merge_properties(
- entities, base_entity, strategy
+ entities, base_entity, strategy, tracking_id=tracking_id
)
# Step 3: Merge relationships
@@ -370,18 +397,25 @@ class MergeStrategyManager:
entities: List[Dict[str, Any]],
base_entity: Dict[str, Any],
strategy: MergeStrategy,
+ tracking_id: Optional[str] = None,
) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
"""Merge properties from all entities."""
merged_properties = base_entity.get("properties", {}).copy()
conflicts = []
- for entity in entities:
+ total_entities = len(entities) - 1 # Excluding base entity
+ if total_entities <= 0:
+ return merged_properties, conflicts
+
+ for ent_idx, entity in enumerate(entities):
if entity == base_entity:
continue
entity_props = entity.get("properties", {})
+ prop_list = list(entity_props.items())
+ total_props = len(prop_list)
- for prop_name, prop_value in entity_props.items():
+ for prop_idx, (prop_name, prop_value) in enumerate(prop_list):
if prop_name not in merged_properties:
# New property, add it
merged_properties[prop_name] = prop_value
@@ -401,6 +435,14 @@ class MergeStrategyManager:
"resolution": conflict.get("resolution"),
}
)
+
+ # Update progress if tracking_id is provided
+ if tracking_id and (prop_idx % 10 == 0 or prop_idx == total_props - 1):
+ processed_entities = ent_idx
+ # Calculate overall progress across all entities and their properties
+ # This is an approximation for smoother progress
+ progress_msg = f"Merging properties from entity {ent_idx+1}/{len(entities)}: {prop_name}"
+ self.progress_tracker.update_tracking(tracking_id, message=progress_msg)
return merged_properties, conflicts
diff --git a/semantica/deduplication/similarity_calculator.py b/semantica/deduplication/similarity_calculator.py
index 39e8895e..b1e38abe 100644
--- a/semantica/deduplication/similarity_calculator.py
+++ b/semantica/deduplication/similarity_calculator.py
@@ -7,6 +7,9 @@ metrics including string similarity, property similarity, relationship similarit
and embedding similarity.
Algorithms Used:
+ - Blocking Strategy: Prefix-based entity grouping to reduce O(n²) comparisons
+ - Pre-processing: Vectorized preparation of lowercase names and relationship sets
+ - Short-circuiting: Early exit for dissimilar pairs based on name similarity
- Levenshtein Distance: Dynamic programming algorithm for edit distance calculation
- Jaro Similarity: Character-based similarity with match window algorithm
- Jaro-Winkler Similarity: Jaro with prefix bonus (up to 4 characters, 0.1 weight)
@@ -16,6 +19,7 @@ Algorithms Used:
- Multi-factor Aggregation: Weighted sum of similarity components with normalization
Key Features:
+ - Blocking strategy and short-circuiting for high-performance large-scale processing
- Multi-factor similarity calculation (string, property, relationship, embedding)
- Multiple string similarity algorithms (Levenshtein, Jaro-Winkler, cosine)
- Weighted aggregation of similarity components with automatic normalization
@@ -146,7 +150,7 @@ class SimilarityCalculator:
self.logger.debug("Similarity calculator initialized")
def calculate_similarity(
- self, entity1: Dict[str, Any], entity2: Dict[str, Any], **options
+ self, entity1: Dict[str, Any], entity2: Dict[str, Any], track: bool = True, **options
) -> SimilarityResult:
"""
Calculate overall similarity between two entities.
@@ -156,63 +160,69 @@ class SimilarityCalculator:
similarity, and embedding similarity (if available). Results are aggregated
using configurable weights.
- Similarity Components:
- - String: Name/identifier similarity (Levenshtein, Jaro-Winkler, etc.)
- - Property: Property value similarity
- - Relationship: Relationship overlap (Jaccard similarity)
- - Embedding: Cosine similarity of embeddings (if available)
-
Args:
- entity1: First entity dictionary. Should have "name" field and optionally
- "properties", "relationships", and "embedding" fields.
- entity2: Second entity dictionary (same structure as entity1)
- **options: Additional calculation options (currently unused)
+ entity1: First entity dictionary
+ entity2: Second entity dictionary
+ track: Whether to track progress for this individual calculation (default: True)
+ **options: Additional calculation options
Returns:
- SimilarityResult object containing:
- - score: Overall similarity score (0.0 to 1.0)
- - method: Calculation method used ("multi_factor")
- - components: Dict of individual component scores
- - metadata: Weights used for aggregation
-
- Example:
- >>> entity1 = {"name": "Apple Inc.", "type": "Company"}
- >>> entity2 = {"name": "Apple", "type": "Company"}
- >>> result = calculator.calculate_similarity(entity1, entity2)
- >>> print(f"Similarity: {result.score:.2f}")
- >>> print(f"Components: {result.components}")
+ SimilarityResult object
"""
- # Track similarity calculation
- tracking_id = self.progress_tracker.start_tracking(
- file=None,
- module="deduplication",
- submodule="SimilarityCalculator",
- message="Calculating similarity between entities",
- )
+ tracking_id = None
+ if track:
+ # Track similarity calculation
+ tracking_id = self.progress_tracker.start_tracking(
+ file=None,
+ module="deduplication",
+ submodule="SimilarityCalculator",
+ message="Calculating similarity between entities",
+ )
try:
components = {}
- # String similarity
- self.progress_tracker.update_tracking(
- tracking_id, message="Calculating string similarity..."
- )
- string_score = self.calculate_string_similarity(
- entity1.get("name", ""), entity2.get("name", "")
- )
+ # String similarity (usually the most important and fastest)
+ if tracking_id:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Calculating string similarity..."
+ )
+
+ # Use pre-calculated lowercase name if available
+ name1 = entity1.get("_lower_name")
+ if name1 is None:
+ name1 = entity1.get("name") or entity1.get("text") or ""
+
+ name2 = entity2.get("_lower_name")
+ if name2 is None:
+ name2 = entity2.get("name") or entity2.get("text") or ""
+
+ string_score = self.calculate_string_similarity(name1, name2)
components["string"] = string_score
+ # Short-circuit if string similarity is too low and weight is high
+ # If string similarity is 0 and it accounts for 60% of score,
+ # max possible score is 0.4, which is below most thresholds.
+ if self.string_weight > 0.5 and string_score < 0.3 and not ("embedding" in entity1 and "embedding" in entity2):
+ # Only short-circuit if no embeddings (which might provide semantic similarity)
+ # and string similarity is very low.
+ overall_score = string_score * self.string_weight # Rough estimate
+ if overall_score < (options.get("threshold") or self.similarity_threshold) * 0.5:
+ return SimilarityResult(score=overall_score, method="short_circuit", components=components)
+
# Property similarity
- self.progress_tracker.update_tracking(
- tracking_id, message="Calculating property similarity..."
- )
+ if tracking_id:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Calculating property similarity..."
+ )
property_score = self.calculate_property_similarity(entity1, entity2)
components["property"] = property_score
# Relationship similarity
- self.progress_tracker.update_tracking(
- tracking_id, message="Calculating relationship similarity..."
- )
+ if tracking_id:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Calculating relationship similarity..."
+ )
relationship_score = self.calculate_relationship_similarity(
entity1, entity2
)
@@ -221,18 +231,20 @@ class SimilarityCalculator:
# Embedding similarity (if available)
embedding_score = 0.0
if "embedding" in entity1 and "embedding" in entity2:
- self.progress_tracker.update_tracking(
- tracking_id, message="Calculating embedding similarity..."
- )
+ if tracking_id:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Calculating embedding similarity..."
+ )
embedding_score = self.calculate_embedding_similarity(
entity1["embedding"], entity2["embedding"]
)
components["embedding"] = embedding_score
# Weighted aggregation
- self.progress_tracker.update_tracking(
- tracking_id, message="Aggregating similarity scores..."
- )
+ if tracking_id:
+ self.progress_tracker.update_tracking(
+ tracking_id, message="Aggregating similarity scores..."
+ )
weights = {
"string": self.string_weight,
"property": self.property_weight,
@@ -251,11 +263,12 @@ class SimilarityCalculator:
components.get(key, 0.0) * weight for key, weight in weights.items()
)
- self.progress_tracker.stop_tracking(
- tracking_id,
- status="completed",
- message=f"Similarity score: {overall_score:.2f}",
- )
+ if tracking_id:
+ self.progress_tracker.stop_tracking(
+ tracking_id,
+ status="completed",
+ message=f"Similarity score: {overall_score:.2f}",
+ )
return SimilarityResult(
score=overall_score,
method="multi_factor",
@@ -264,9 +277,10 @@ class SimilarityCalculator:
)
except Exception as e:
- self.progress_tracker.stop_tracking(
- tracking_id, status="failed", message=str(e)
- )
+ if tracking_id:
+ self.progress_tracker.stop_tracking(
+ tracking_id, status="failed", message=str(e)
+ )
raise
def calculate_string_similarity(
@@ -363,15 +377,16 @@ class SimilarityCalculator:
Returns:
Relationship similarity score (0-1)
"""
- def _make_hashable(item):
- if isinstance(item, dict):
- return tuple(sorted((k, _make_hashable(v)) for k, v in item.items()))
- if isinstance(item, list):
- return tuple(_make_hashable(x) for x in item)
- return item
-
- rels1 = set(_make_hashable(r) for r in entity1.get("relationships", []))
- rels2 = set(_make_hashable(r) for r in entity2.get("relationships", []))
+ # Use pre-calculated hashable relationships if available
+ if "_hashable_rels" in entity1:
+ rels1 = entity1["_hashable_rels"]
+ else:
+ rels1 = set(self._make_hashable(r) for r in entity1.get("relationships", []))
+
+ if "_hashable_rels" in entity2:
+ rels2 = entity2["_hashable_rels"]
+ else:
+ rels2 = set(self._make_hashable(r) for r in entity2.get("relationships", []))
if not rels1 and not rels2:
return 0.5
@@ -384,6 +399,14 @@ class SimilarityCalculator:
return len(intersection) / len(union) if union else 0.0
+ def _make_hashable(self, item: Any) -> Any:
+ """Convert item to hashable form for set operations."""
+ if isinstance(item, dict):
+ return tuple(sorted((k, self._make_hashable(v)) for k, v in item.items()))
+ if isinstance(item, list):
+ return tuple(self._make_hashable(x) for x in item)
+ return item
+
def calculate_embedding_similarity(
self, embedding1: List[float], embedding2: List[float]
) -> float:
@@ -536,11 +559,14 @@ class SimilarityCalculator:
self, entities: List[Dict[str, Any]], threshold: Optional[float] = None
) -> List[Tuple[Dict[str, Any], Dict[str, Any], float]]:
"""
- Calculate similarity for all pairs of entities.
+ Calculate similarity for all entity pairs in a batch.
+
+ This method optimizes calculation by comparing only pairs that are likely
+ to be similar using a blocking/indexing strategy.
Args:
- entities: List of entities
- threshold: Minimum similarity threshold
+ entities: List of entity dictionaries
+ threshold: Similarity threshold for filtering (default: self.similarity_threshold)
Returns:
List of (entity1, entity2, similarity) tuples
@@ -557,59 +583,98 @@ class SimilarityCalculator:
threshold = threshold or self.similarity_threshold
results = []
- # Calculate total pairs: n*(n-1)/2
- total_pairs = len(entities) * (len(entities) - 1) // 2
+ # Pre-process entities for faster comparison
+ # 1. Pre-calculate hashable relationships
+ # 2. Pre-calculate lowercase names
+ # 3. Pre-calculate property sets
+ processed_entities = []
+ for entity in entities:
+ # Handle both dicts and Entity objects
+ if hasattr(entity, "__dict__"):
+ processed_entity = vars(entity).copy()
+ elif isinstance(entity, dict):
+ processed_entity = entity.copy()
+ else:
+ processed_entity = {"_original": entity}
+
+ # Pre-calculate hashable relationships for Jaccard similarity
+ # Handle both 'relationships' and 'metadata.relationships'
+ rels = processed_entity.get("relationships")
+ if rels is None and "metadata" in processed_entity:
+ rels = processed_entity["metadata"].get("relationships")
+
+ if rels:
+ processed_entity["_hashable_rels"] = set(self._make_hashable(r) for r in rels)
+ else:
+ processed_entity["_hashable_rels"] = set()
+
+ # Pre-calculate lowercase name
+ # Handle both 'name' and 'text' (used in Entity class)
+ name = processed_entity.get("name") or processed_entity.get("text") or ""
+ processed_entity["_lower_name"] = name.lower().strip()
+
+ processed_entities.append(processed_entity)
+
+ # Blocking strategy: Group entities by first character of name
+ # This significantly reduces the number of pairs to compare while
+ # still catching most duplicates.
+ blocks: Dict[str, List[int]] = {}
+ for idx, entity in enumerate(processed_entities):
+ name = entity["_lower_name"]
+ if not name:
+ block_key = "___empty___"
+ else:
+ # Use the first character as the block key
+ block_key = name[0]
+
+ if block_key not in blocks:
+ blocks[block_key] = []
+ blocks[block_key].append(idx)
+
+ # Calculate total potential pairs within blocks for progress tracking
+ total_pairs = 0
+ for block_indices in blocks.values():
+ n = len(block_indices)
+ total_pairs += n * (n - 1) // 2
+
processed = 0
- # Update more frequently: every 1% or at least every 10 items, but always update for small datasets
+ # Update more frequently: every 1% or at least every 10 items
if total_pairs <= 10:
- update_interval = 1 # Update every item for small datasets
+ update_interval = 1
else:
- update_interval = max(1, min(10, total_pairs // 100))
+ update_interval = max(1, min(100, total_pairs // 100))
- # Initial progress update to show tracking started - ALWAYS show this
self.progress_tracker.update_tracking(
tracking_id,
status="running",
- message=f"Calculating similarity for {len(entities)} entities ({total_pairs} pairs)..."
+ message=f"Comparing {total_pairs} pairs across {len(blocks)} blocks..."
)
- # Always show initial progress, even if total_pairs is 0
- remaining = total_pairs - processed
- self.progress_tracker.update_progress(
- tracking_id,
- processed=0,
- total=total_pairs,
- message=f"Starting similarity calculation... 0/{total_pairs} (remaining: {remaining})"
- )
-
- for i in range(len(entities)):
- for j in range(i + 1, len(entities)):
- similarity = self.calculate_similarity(entities[i], entities[j])
-
- if similarity.score >= threshold:
- results.append((entities[i], entities[j], similarity.score))
-
- processed += 1
- remaining = total_pairs - processed
- # Update progress: always update for small datasets, or at intervals for large ones
- should_update = (
- processed % update_interval == 0 or
- processed == total_pairs or
- processed == 1 or
- total_pairs <= 10 # Always update for small datasets
- )
- if should_update:
- self.progress_tracker.update_progress(
- tracking_id,
- processed=processed,
- total=total_pairs,
- message=f"Comparing entity pairs... {processed}/{total_pairs} (remaining: {remaining})"
- )
+ # Compare entities within each block
+ for block_key, indices in blocks.items():
+ for i_idx in range(len(indices)):
+ for j_idx in range(i_idx + 1, len(indices)):
+ i = indices[i_idx]
+ j = indices[j_idx]
+
+ similarity = self.calculate_similarity(processed_entities[i], processed_entities[j], track=False)
+
+ if similarity.score >= threshold:
+ results.append((entities[i], entities[j], similarity.score))
+
+ processed += 1
+ if processed % update_interval == 0 or processed == total_pairs:
+ self.progress_tracker.update_progress(
+ tracking_id,
+ processed=processed,
+ total=total_pairs,
+ message=f"Comparing pairs in block '{block_key}'... {processed}/{total_pairs}"
+ )
self.progress_tracker.stop_tracking(
tracking_id,
status="completed",
- message=f"Found {len(results)} similar pairs",
+ message=f"Found {len(results)} similar pairs across {len(blocks)} blocks",
)
return results
diff --git a/semantica/utils/progress_tracker.py b/semantica/utils/progress_tracker.py
index 2b5a66a7..31d7f154 100644
--- a/semantica/utils/progress_tracker.py
+++ b/semantica/utils/progress_tracker.py
@@ -6,7 +6,9 @@ for file, module, and submodule processing across console, log files, and Jupyte
Key Features:
- Automatic module/submodule detection via introspection
- - Real-time progress updates with emojis
+ - Real-time progress updates with percentages and item counts
+ - Dynamic update intervals based on dataset size for performance
+ - Consolidated display for concurrent tasks to prevent scrolling
- Console, Jupyter notebook, and log file support
- Zero configuration required - works automatically
- Final summary display
@@ -172,15 +174,6 @@ class ConsoleProgressDisplay(ProgressDisplay):
def _get_action_message(self, module: Optional[str], message: str) -> str:
"""Get action message based on module."""
- # Extract action from message if it contains "Semantica:"
- if message and "Semantica:" in message:
- # Use the message as-is if it already has Semantica format
- return (
- message.split("Semantica:")[-1].strip()
- if "Semantica:" in message
- else message
- )
-
# Map modules to actions
action_map = {
"ingest": "is ingesting",
@@ -206,7 +199,17 @@ class ConsoleProgressDisplay(ProgressDisplay):
}
action = action_map.get(module or "", "is processing")
- return f"Semantica {action}"
+ base_msg = f"Semantica {action}"
+
+ if not message:
+ return base_msg
+
+ # If message already contains Semantica format, use it
+ if "Semantica:" in message:
+ return message.split("Semantica:")[-1].strip()
+
+ # Otherwise combine them
+ return f"{base_msg}: {message}"
def _safe_write(self, text: str) -> None:
"""Safely write text to stdout handling encoding errors."""
@@ -225,6 +228,7 @@ class ConsoleProgressDisplay(ProgressDisplay):
return
with self.lock:
+ # Create unique key for this item
key = f"{item.module}:{item.submodule}"
if item.file:
key = f"{item.file}:{key}"
@@ -236,60 +240,48 @@ class ConsoleProgressDisplay(ProgressDisplay):
if self.use_emoji:
parts.append("🧠")
- # Create action message based on module
+ # Create action message based on module (now includes custom message)
action_msg = self._get_action_message(item.module, item.message)
parts.append(action_msg)
- # Status emoji
- if self.use_emoji:
- parts.append(self._get_status_emoji(item.status))
-
- # Module emoji
- if item.module and self.use_emoji:
- parts.append(self._get_emoji_for_module(item.module))
-
- # Module name
- if item.module:
- parts.append(f"[{item.module}]")
+ # Progress bar and percentage
+ if item.progress_percentage is not None:
+ pct = item.progress_percentage
+ bar_width = 15
+ filled = int(bar_width * pct / 100)
+ bar = "█" * filled + "░" * (bar_width - filled)
+ parts.append(f"|{bar}| {pct:.1f}%")
- # Submodule
- if item.submodule:
- parts.append(f"{item.submodule}")
+ # Count information [done/total]
+ if item.processed_items is not None and item.total_items is not None:
+ parts.append(f"[{item.processed_items}/{item.total_items}]")
- # File
- if item.file:
- file_name = Path(item.file).name if item.file else ""
- parts.append(f"📄 {file_name}")
+ # Status and Module emojis
+ if self.use_emoji:
+ status_emoji = self._get_status_emoji(item.status)
+ module_emoji = self._get_emoji_for_module(item.module or "")
+ parts.append(f"{status_emoji}{module_emoji}")
- # Progress information
- progress_parts = []
- if item.progress_percentage is not None:
- progress_parts.append(f"{item.progress_percentage:.1f}%")
-
- if item.processed_items is not None and item.total_items is not None:
- progress_parts.append(f"{item.processed_items}/{item.total_items}")
-
+ # ETA and Rate
+ metrics = []
if item.estimated_remaining is not None and item.estimated_remaining > 0:
- # Format ETA in human-readable format
if item.estimated_remaining < 60:
- eta_str = f"ETA: {item.estimated_remaining:.1f}s"
+ metrics.append(f"ETA: {item.estimated_remaining:.1f}s")
elif item.estimated_remaining < 3600:
- eta_str = f"ETA: {item.estimated_remaining/60:.1f}m"
+ metrics.append(f"ETA: {item.estimated_remaining/60:.1f}m")
else:
- eta_str = f"ETA: {item.estimated_remaining/3600:.1f}h"
- progress_parts.append(eta_str)
+ metrics.append(f"ETA: {item.estimated_remaining/3600:.1f}h")
- # Calculate and show processing rate
if item.start_time and item.processed_items is not None and item.processed_items > 0:
elapsed = time.time() - item.start_time
if elapsed > 0:
rate = item.processed_items / elapsed
- progress_parts.append(f"Rate: {rate:.1f}/s")
+ metrics.append(f"{rate:.1f}/s")
- if progress_parts:
- parts.append(f"({' | '.join(progress_parts)})")
+ if metrics:
+ parts.append(f"({' | '.join(metrics)})")
- # Time elapsed (if no progress info shown)
+ # Elapsed time if no progress info
if item.start_time and item.progress_percentage is None:
elapsed = time.time() - item.start_time
parts.append(f"({elapsed:.1f}s)")
@@ -297,14 +289,16 @@ class ConsoleProgressDisplay(ProgressDisplay):
line = " ".join(parts)
self.current_lines[key] = line
- # Print all current lines (overwrite previous)
- self._safe_write("\r" + " " * 100 + "\r") # Clear line
+ # Print all current lines
+ # For multiple lines, we combine them to avoid console scrolling issues
+ sys.stdout.write("\r" + " " * 120 + "\r")
if len(self.current_lines) == 1:
- self._safe_write(line)
+ sys.stdout.write(line)
else:
- # Multiple items - show all
+ # Combine multiple active lines onto one or two lines to be safe
lines_list = list(self.current_lines.values())
- self._safe_write("\n".join(lines_list[-3:])) # Show last 3
+ sys.stdout.write(" | ".join(lines_list[-2:]))
+
sys.stdout.flush()
def show_summary(self, items: List[ProgressItem]) -> None: