Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Add progress tracking to vector_store and visualization modules
KaifAhmad14cca9c6ac560
diff --git a/semantica/triple_store/blazegraph_adapter.py b/semantica/triple_store/blazegraph_adapter.pyindex a47dcbb1..977104f4 100644--- a/semantica/triple_store/blazegraph_adapter.py+++ b/semantica/triple_store/blazegraph_adapter.py@@ -33,6 +33,7 @@ from urllib.parse import urljoinfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..semantic_extract.triple_extractor import Triple@@ -62,6 +63,7 @@ class BlazegraphAdapter:"""self.logger = get_logger("blazegraph_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.endpoint = endpoint.rstrip('/')self.namespace = config.get("namespace", "kb")@@ -115,12 +117,20 @@ class BlazegraphAdapter:Returns:Query results"""- if not self.connected:- raise ProcessingError("Not connected to Blazegraph")-- sparql_endpoint = self._get_sparql_endpoint()+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="BlazegraphAdapter",+ message="Executing SPARQL query on Blazegraph"+ )try:+ if not self.connected:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Not connected to Blazegraph")+ raise ProcessingError("Not connected to Blazegraph")++ sparql_endpoint = self._get_sparql_endpoint()++ self.progress_tracker.update_tracking(tracking_id, message="Sending query to Blazegraph endpoint...")response = requests.post(sparql_endpoint,data={"query": query},@@ -132,9 +142,10 @@ class BlazegraphAdapter:response.raise_for_status()# Parse JSON response+ self.progress_tracker.update_tracking(tracking_id, message="Parsing query results...")result_data = response.json()- return {+ result = {"success": True,"bindings": result_data.get("results", {}).get("bindings", []),"variables": result_data.get("head", {}).get("vars", []),@@ -143,8 +154,13 @@ class BlazegraphAdapter:"endpoint": sparql_endpoint}}++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Query executed: {len(result['bindings'])} results")+ return resultexcept Exception as e:self.logger.error(f"SPARQL query failed: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"SPARQL query failed: {e}")def bulk_load(diff --git a/semantica/triple_store/bulk_loader.py b/semantica/triple_store/bulk_loader.pyindex 8cd099d9..77558bb6 100644--- a/semantica/triple_store/bulk_loader.py+++ b/semantica/triple_store/bulk_loader.py@@ -35,6 +35,7 @@ import timefrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..semantic_extract.triple_extractor import Triple@@ -78,6 +79,7 @@ class BulkLoader:self.logger = get_logger("bulk_loader")self.config = config or {}self.config.update(kwargs)+ self.progress_tracker = get_progress_tracker()self.batch_size = self.config.get("batch_size", 1000)self.max_retries = self.config.get("max_retries", 3)@@ -103,102 +105,117 @@ class BulkLoader:Returns:Load progress information"""- start_time = time.time()- batch_size = options.get("batch_size", self.batch_size)- stop_on_error = options.get("stop_on_error", False)- progress_callback = options.get("progress_callback")-- total_triples = len(triples)- total_batches = (total_triples + batch_size - 1) // batch_size-- loaded_count = 0- failed_count = 0-- self.logger.info(f"Starting bulk load: {total_triples} triples in {total_batches} batches")+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="BulkLoader",+ message=f"Loading {len(triples)} triples in bulk"+ )- # Process in batches- for batch_num in range(total_batches):- batch_start = batch_num * batch_size- batch_end = min(batch_start + batch_size, total_triples)- batch = triples[batch_start:batch_end]+ try:+ start_time = time.time()+ batch_size = options.get("batch_size", self.batch_size)+ stop_on_error = options.get("stop_on_error", False)+ progress_callback = options.get("progress_callback")- # Load batch with retries- batch_loaded = 0- for attempt in range(self.max_retries):- try:- if hasattr(store_adapter, "bulk_load"):- result = store_adapter.bulk_load(batch, **options)- elif hasattr(store_adapter, "add_triples"):- result = store_adapter.add_triples(batch, **options)- else:- raise ProcessingError("Store adapter does not support bulk loading")-- batch_loaded = len(batch)- loaded_count += batch_loaded- break-- except Exception as e:- if attempt < self.max_retries - 1:- self.logger.warning(f"Batch {batch_num} failed, retrying: {e}")- time.sleep(self.retry_delay * (attempt + 1))- else:- self.logger.error(f"Batch {batch_num} failed after {self.max_retries} attempts: {e}")- failed_count += len(batch)+ total_triples = len(triples)+ total_batches = (total_triples + batch_size - 1) // batch_size++ loaded_count = 0+ failed_count = 0++ self.logger.info(f"Starting bulk load: {total_triples} triples in {total_batches} batches")++ # Process in batches+ for batch_num in range(total_batches):+ self.progress_tracker.update_tracking(tracking_id, message=f"Processing batch {batch_num + 1}/{total_batches}...")+ batch_start = batch_num * batch_size+ batch_end = min(batch_start + batch_size, total_triples)+ batch = triples[batch_start:batch_end]++ # Load batch with retries+ batch_loaded = 0+ for attempt in range(self.max_retries):+ try:+ if hasattr(store_adapter, "bulk_load"):+ result = store_adapter.bulk_load(batch, **options)+ elif hasattr(store_adapter, "add_triples"):+ result = store_adapter.add_triples(batch, **options)+ else:+ raise ProcessingError("Store adapter does not support bulk loading")++ batch_loaded = len(batch)+ loaded_count += batch_loaded+ break- if stop_on_error:- raise ProcessingError(f"Bulk load stopped due to error: {e}")+ except Exception as e:+ if attempt < self.max_retries - 1:+ self.logger.warning(f"Batch {batch_num} failed, retrying: {e}")+ time.sleep(self.retry_delay * (attempt + 1))+ else:+ self.logger.error(f"Batch {batch_num} failed after {self.max_retries} attempts: {e}")+ failed_count += len(batch)++ if stop_on_error:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=f"Bulk load stopped due to error: {e}")+ raise ProcessingError(f"Bulk load stopped due to error: {e}")++ # Update progress+ elapsed = time.time() - start_time+ progress = (loaded_count / total_triples * 100) if total_triples > 0 else 0.0+ estimated_remaining = None+ if loaded_count > 0:+ estimated_remaining = (elapsed / loaded_count) * (total_triples - loaded_count)++ progress_info = LoadProgress(+ total_triples=total_triples,+ loaded_triples=loaded_count,+ failed_triples=failed_count,+ current_batch=batch_num + 1,+ total_batches=total_batches,+ progress_percentage=progress,+ elapsed_time=elapsed,+ estimated_remaining=estimated_remaining,+ metadata={+ "batch_size": batch_size,+ "store_type": store_adapter.__class__.__name__+ }+ )++ # Call progress callback if provided+ if progress_callback:+ progress_callback(progress_info)++ self.logger.debug(f"Progress: {progress:.1f}% ({loaded_count}/{total_triples} triples)")- # Update progresselapsed = time.time() - start_time- progress = (loaded_count / total_triples * 100) if total_triples > 0 else 0.0- estimated_remaining = None- if loaded_count > 0:- estimated_remaining = (elapsed / loaded_count) * (total_triples - loaded_count)- progress_info = LoadProgress(+ final_progress = LoadProgress(total_triples=total_triples,loaded_triples=loaded_count,failed_triples=failed_count,- current_batch=batch_num + 1,+ current_batch=total_batches,total_batches=total_batches,- progress_percentage=progress,+ progress_percentage=100.0,elapsed_time=elapsed,- estimated_remaining=estimated_remaining,+ estimated_remaining=0.0,metadata={- "batch_size": batch_size,- "store_type": store_adapter.__class__.__name__+ "success": failed_count == 0,+ "throughput": loaded_count / elapsed if elapsed > 0 else 0.0})- # Call progress callback if provided- if progress_callback:- progress_callback(progress_info)+ self.logger.info(+ f"Bulk load completed: {loaded_count}/{total_triples} triples loaded "+ f"in {elapsed:.2f}s ({loaded_count / elapsed:.0f} triples/sec)"+ )- self.logger.debug(f"Progress: {progress:.1f}% ({loaded_count}/{total_triples} triples)")-- elapsed = time.time() - start_time-- final_progress = LoadProgress(- total_triples=total_triples,- loaded_triples=loaded_count,- failed_triples=failed_count,- current_batch=total_batches,- total_batches=total_batches,- progress_percentage=100.0,- elapsed_time=elapsed,- estimated_remaining=0.0,- metadata={- "success": failed_count == 0,- "throughput": loaded_count / elapsed if elapsed > 0 else 0.0- }- )-- self.logger.info(- f"Bulk load completed: {loaded_count}/{total_triples} triples loaded "- f"in {elapsed:.2f}s ({loaded_count / elapsed:.0f} triples/sec)"- )-- return final_progress+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Bulk load completed: {loaded_count}/{total_triples} triples loaded")+ return final_progress++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef load_from_file(self,diff --git a/semantica/triple_store/jena_adapter.py b/semantica/triple_store/jena_adapter.pyindex b5c82430..148f674a 100644--- a/semantica/triple_store/jena_adapter.py+++ b/semantica/triple_store/jena_adapter.py@@ -30,6 +30,7 @@ from typing import Any, Dict, List, Optionalfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..semantic_extract.triple_extractor import Triple# Optional Jena imports@@ -67,6 +68,7 @@ class JenaAdapter:"""self.logger = get_logger("jena_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.endpoint = config.get("endpoint")self.dataset = config.get("dataset", "default")@@ -127,11 +129,19 @@ class JenaAdapter:Returns:Operation status"""- if not self.graph:- raise ProcessingError("Graph not initialized")+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="JenaAdapter",+ message=f"Adding {len(triples)} triples to Jena model"+ )try:+ if not self.graph:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Graph not initialized")+ raise ProcessingError("Graph not initialized")+added_count = 0+ self.progress_tracker.update_tracking(tracking_id, message="Adding triples to graph...")for triple in triples:try:subject = URIRef(triple.subject)@@ -143,6 +153,8 @@ class JenaAdapter:except Exception as e:self.logger.warning(f"Failed to add triple: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Added {added_count}/{len(triples)} triples")return {"success": True,"added": added_count,@@ -150,6 +162,7 @@ class JenaAdapter:}except Exception as e:self.logger.error(f"Failed to add triples: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Failed to add triples: {e}")def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:diff --git a/semantica/triple_store/query_engine.py b/semantica/triple_store/query_engine.pyindex f37392f0..e8d42efd 100644--- a/semantica/triple_store/query_engine.py+++ b/semantica/triple_store/query_engine.py@@ -37,6 +37,7 @@ import timefrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -84,6 +85,7 @@ class QueryEngine:self.logger = get_logger("query_engine")self.config = config or {}self.config.update(kwargs)+ self.progress_tracker = get_progress_tracker()self.enable_caching = self.config.get("enable_caching", True)self.enable_optimization = self.config.get("enable_optimization", True)@@ -109,29 +111,41 @@ class QueryEngine:Returns:Query result"""- start_time = time.time()-- # Validate query- if not self._validate_query(query):- raise ValidationError("Invalid SPARQL query")-- # Check cache- if self.enable_caching:- cache_key = self._get_cache_key(query)- if cache_key in self.query_cache:- self.logger.debug("Returning cached query result")- cached_result = self.query_cache[cache_key]- cached_result.metadata["cached"] = True- return cached_result-- # Optimize query- if self.enable_optimization:- optimized_query = self.optimize_query(query, **options)- else:- optimized_query = query+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="QueryEngine",+ message="Executing SPARQL query"+ )- # Execute querytry:+ start_time = time.time()++ # Validate query+ self.progress_tracker.update_tracking(tracking_id, message="Validating query...")+ if not self._validate_query(query):+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Invalid SPARQL query")+ raise ValidationError("Invalid SPARQL query")++ # Check cache+ if self.enable_caching:+ self.progress_tracker.update_tracking(tracking_id, message="Checking cache...")+ cache_key = self._get_cache_key(query)+ if cache_key in self.query_cache:+ self.logger.debug("Returning cached query result")+ cached_result = self.query_cache[cache_key]+ cached_result.metadata["cached"] = True+ self.progress_tracker.stop_tracking(tracking_id, status="completed", message="Returned cached result")+ return cached_result++ # Optimize query+ if self.enable_optimization:+ self.progress_tracker.update_tracking(tracking_id, message="Optimizing query...")+ optimized_query = self.optimize_query(query, **options)+ else:+ optimized_query = query++ # Execute query+ self.progress_tracker.update_tracking(tracking_id, message="Executing query on store...")if hasattr(store_adapter, "execute_sparql"):result_data = store_adapter.execute_sparql(optimized_query, **options)else:@@ -152,6 +166,7 @@ class QueryEngine:# Cache resultif self.enable_caching:+ self.progress_tracker.update_tracking(tracking_id, message="Caching result...")self._cache_result(query, result)# Record history@@ -162,11 +177,14 @@ class QueryEngine:"timestamp": datetime.now().isoformat()})+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Query executed: {len(result.bindings)} results in {execution_time:.2f}s")return resultexcept Exception as e:- execution_time = time.time() - start_time+ execution_time = time.time() - start_time if 'start_time' in locals() else 0.0self.logger.error(f"Query execution failed: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Query execution failed: {e}")def optimize_query(diff --git a/semantica/triple_store/rdf4j_adapter.py b/semantica/triple_store/rdf4j_adapter.pyindex 8bb26fb6..10736a0b 100644--- a/semantica/triple_store/rdf4j_adapter.py+++ b/semantica/triple_store/rdf4j_adapter.py@@ -31,6 +31,7 @@ import requestsfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..semantic_extract.triple_extractor import Triple@@ -60,6 +61,7 @@ class RDF4JAdapter:"""self.logger = get_logger("rdf4j_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.endpoint = endpoint.rstrip('/')self.repository_id = config.get("repository_id", "default")@@ -176,12 +178,20 @@ class RDF4JAdapter:Returns:Query results"""- if not self.connected:- raise ProcessingError("Not connected to RDF4J")-- sparql_endpoint = self._get_sparql_endpoint()+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="RDF4JAdapter",+ message="Executing SPARQL query on RDF4J"+ )try:+ if not self.connected:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Not connected to RDF4J")+ raise ProcessingError("Not connected to RDF4J")++ sparql_endpoint = self._get_sparql_endpoint()++ self.progress_tracker.update_tracking(tracking_id, message="Sending query to RDF4J endpoint...")response = requests.post(sparql_endpoint,data={"query": query},@@ -192,9 +202,10 @@ class RDF4JAdapter:response.raise_for_status()+ self.progress_tracker.update_tracking(tracking_id, message="Parsing query results...")result_data = response.json()- return {+ result = {"success": True,"bindings": result_data.get("results", {}).get("bindings", []),"variables": result_data.get("head", {}).get("vars", []),@@ -203,8 +214,13 @@ class RDF4JAdapter:"endpoint": sparql_endpoint}}++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Query executed: {len(result['bindings'])} results")+ return resultexcept Exception as e:self.logger.error(f"SPARQL query failed: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"SPARQL query failed: {e}")def add_triples(@@ -222,15 +238,24 @@ class RDF4JAdapter:Returns:Operation status"""- if not self.connected:- raise ProcessingError("Not connected to RDF4J")-- update_endpoint = self._get_update_endpoint()-- # Convert triples to RDF format- rdf_data = self._triples_to_ntriples(triples)+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="RDF4JAdapter",+ message=f"Adding {len(triples)} triples to RDF4J repository"+ )try:+ if not self.connected:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Not connected to RDF4J")+ raise ProcessingError("Not connected to RDF4J")++ update_endpoint = self._get_update_endpoint()++ # Convert triples to RDF format+ self.progress_tracker.update_tracking(tracking_id, message="Converting triples to RDF format...")+ rdf_data = self._triples_to_ntriples(triples)++ self.progress_tracker.update_tracking(tracking_id, message="Sending triples to RDF4J repository...")response = requests.post(update_endpoint,data=rdf_data,@@ -241,12 +266,16 @@ class RDF4JAdapter:response.raise_for_status()+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Added {len(triples)} triples to repository")+return {"success": True,"triples_added": len(triples)}except Exception as e:self.logger.error(f"Add triples failed: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Add triples failed: {e}")def add_triple(self, triple: Triple, **options) -> Dict[str, Any]:diff --git a/semantica/triple_store/triple_manager.py b/semantica/triple_store/triple_manager.pyindex c2918f29..6d643c29 100644--- a/semantica/triple_store/triple_manager.py+++ b/semantica/triple_store/triple_manager.py@@ -34,6 +34,7 @@ from dataclasses import dataclass, fieldfrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..semantic_extract.triple_extractor import Triple@@ -71,6 +72,7 @@ class TripleManager:self.logger = get_logger("triple_manager")self.config = config or {}self.config.update(kwargs)+ self.progress_tracker = get_progress_tracker()self.stores: Dict[str, TripleStore] = {}self.default_store_id = self.config.get("default_store")@@ -167,28 +169,40 @@ class TripleManager:Returns:Operation status"""- store = self._get_store(store_id)-- # Validate triples- if options.get("validate", True):- valid_triples = [t for t in triples if self._validate_triple(t)]- invalid_count = len(triples) - len(valid_triples)- if invalid_count > 0:- self.logger.warning(f"{invalid_count} invalid triples filtered out")- else:- valid_triples = triples+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="TripleManager",+ message=f"Adding {len(triples)} triples to store"+ )- # Add to storetry:+ store = self._get_store(store_id)++ # Validate triples+ if options.get("validate", True):+ self.progress_tracker.update_tracking(tracking_id, message="Validating triples...")+ valid_triples = [t for t in triples if self._validate_triple(t)]+ invalid_count = len(triples) - len(valid_triples)+ if invalid_count > 0:+ self.logger.warning(f"{invalid_count} invalid triples filtered out")+ else:+ valid_triples = triples++ # Add to storeadapter = self._get_adapter(store)batch_size = options.get("batch_size", 1000)+ total_batches = (len(valid_triples) + batch_size - 1) // batch_sizeresults = []for i in range(0, len(valid_triples), batch_size):+ batch_num = i // batch_size + 1+ self.progress_tracker.update_tracking(tracking_id, message=f"Processing batch {batch_num}/{total_batches}...")batch = valid_triples[i:i + batch_size]result = adapter.add_triples(batch, **options)results.append(result)+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Added {len(valid_triples)} triples in {len(results)} batches")return {"success": True,"store_id": store.store_id,@@ -198,6 +212,7 @@ class TripleManager:}except Exception as e:self.logger.error(f"Failed to add triples: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Failed to add triples: {e}")def get_triple(diff --git a/semantica/triple_store/virtuoso_adapter.py b/semantica/triple_store/virtuoso_adapter.pyindex bb8358bc..d5fb345d 100644--- a/semantica/triple_store/virtuoso_adapter.py+++ b/semantica/triple_store/virtuoso_adapter.py@@ -61,6 +61,7 @@ class VirtuosoAdapter:"""self.logger = get_logger("virtuoso_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.endpoint = endpoint.rstrip('/')self.username = config.get("username", "dba")@@ -148,12 +149,20 @@ class VirtuosoAdapter:Returns:Query results"""- if not self.connected:- raise ProcessingError("Not connected to Virtuoso")-- sparql_endpoint = self._get_sparql_endpoint()+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="VirtuosoAdapter",+ message="Executing SPARQL query on Virtuoso"+ )try:+ if not self.connected:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Not connected to Virtuoso")+ raise ProcessingError("Not connected to Virtuoso")++ sparql_endpoint = self._get_sparql_endpoint()++ self.progress_tracker.update_tracking(tracking_id, message="Sending query to Virtuoso endpoint...")response = requests.get(sparql_endpoint,params={"query": query, "default-graph-uri": self.default_graph} if self.default_graph else {"query": query},@@ -164,9 +173,10 @@ class VirtuosoAdapter:response.raise_for_status()+ self.progress_tracker.update_tracking(tracking_id, message="Parsing query results...")result_data = response.json()- return {+ result = {"success": True,"bindings": result_data.get("results", {}).get("bindings", []),"variables": result_data.get("head", {}).get("vars", []),@@ -175,8 +185,13 @@ class VirtuosoAdapter:"endpoint": sparql_endpoint}}++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Query executed: {len(result['bindings'])} results")+ return resultexcept Exception as e:self.logger.error(f"SPARQL query failed: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"SPARQL query failed: {e}")def optimize_queries(@@ -225,23 +240,32 @@ class VirtuosoAdapter:Returns:Load status"""- if not self.connected:- raise ProcessingError("Not connected to Virtuoso")-- graph = options.get("graph", self.default_graph)- format = options.get("format", "turtle")-- # Convert triples to RDF- rdf_data = self._triples_to_rdf(triples, format)-- # Use SPARQL INSERT for bulk loading- update_endpoint = self._get_sparql_update_endpoint()-- graph_clause = f"GRAPH <{graph}>" if graph else ""- insert_data = self._build_insert_data(triples)- query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"+ tracking_id = self.progress_tracker.start_tracking(+ module="triple_store",+ submodule="VirtuosoAdapter",+ message=f"Bulk loading {len(triples)} triples to Virtuoso"+ )try:+ if not self.connected:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="Not connected to Virtuoso")+ raise ProcessingError("Not connected to Virtuoso")++ graph = options.get("graph", self.default_graph)+ format = options.get("format", "turtle")++ # Convert triples to RDF+ self.progress_tracker.update_tracking(tracking_id, message="Converting triples to RDF format...")+ rdf_data = self._triples_to_rdf(triples, format)++ # Use SPARQL INSERT for bulk loading+ update_endpoint = self._get_sparql_update_endpoint()++ graph_clause = f"GRAPH <{graph}>" if graph else ""+ insert_data = self._build_insert_data(triples)+ query = f"INSERT DATA {graph_clause} {{ {insert_data} }}"++ self.progress_tracker.update_tracking(tracking_id, message="Sending bulk load request...")response = requests.post(update_endpoint,data={"query": query},@@ -252,6 +276,8 @@ class VirtuosoAdapter:response.raise_for_status()+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Bulk loaded {len(triples)} triples")return {"success": True,"triples_loaded": len(triples),@@ -259,6 +285,7 @@ class VirtuosoAdapter:}except Exception as e:self.logger.error(f"Bulk load failed: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Bulk load failed: {e}")def _triples_to_rdf(self, triples: List[Triple], format: str = "turtle") -> str:diff --git a/semantica/vector_store/faiss_adapter.py b/semantica/vector_store/faiss_adapter.pyindex be1cf473..9ae0f4ba 100644--- a/semantica/vector_store/faiss_adapter.py+++ b/semantica/vector_store/faiss_adapter.py@@ -41,6 +41,7 @@ from pathlib import Pathfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker# Optional FAISS importtry:@@ -225,6 +226,7 @@ class FAISSAdapter:"""Initialize FAISS adapter."""self.logger = get_logger("faiss_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.dimension = dimensionself.index: Optional[FAISSIndex] = None@@ -279,29 +281,46 @@ class FAISSAdapter:Returns:List of vector IDs"""- if self.index is None:- self.create_index(**options)-- # Convert to numpy array- if isinstance(vectors, list):- vectors = np.array(vectors)-- vectors = vectors.astype(np.float32)-- # Generate IDs if not provided- if ids is None:- ids = [f"vec_{len(self.index.vector_ids) + i}" for i in range(len(vectors))]-- # Store metadata- if metadata:- for vec_id, meta in zip(ids, metadata):- self.index.metadata[vec_id] = meta-- # Add vectors to index- self.index.add_vectors(vectors, ids)-- self.logger.info(f"Added {len(vectors)} vectors to FAISS index")- return ids+ num_vectors = len(vectors) if isinstance(vectors, (list, np.ndarray)) else 1+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="FAISSAdapter",+ message=f"Adding {num_vectors} vectors to FAISS index"+ )++ try:+ if self.index is None:+ self.progress_tracker.update_tracking(tracking_id, message="Creating FAISS index...")+ self.create_index(**options)++ # Convert to numpy array+ self.progress_tracker.update_tracking(tracking_id, message="Preparing vectors...")+ if isinstance(vectors, list):+ vectors = np.array(vectors)++ vectors = vectors.astype(np.float32)++ # Generate IDs if not provided+ if ids is None:+ ids = [f"vec_{len(self.index.vector_ids) + i}" for i in range(len(vectors))]++ # Store metadata+ if metadata:+ self.progress_tracker.update_tracking(tracking_id, message="Storing metadata...")+ for vec_id, meta in zip(ids, metadata):+ self.index.metadata[vec_id] = meta++ # Add vectors to index+ self.progress_tracker.update_tracking(tracking_id, message="Adding vectors to index...")+ self.index.add_vectors(vectors, ids)++ self.logger.info(f"Added {len(vectors)} vectors to FAISS index")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Added {len(vectors)} vectors to FAISS index")+ return ids+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef search_similar(self,@@ -320,10 +339,27 @@ class FAISSAdapter:Returns:List of search results"""- if self.search_engine is None:- raise ProcessingError("Index not initialized. Call create_index() first.")-- return self.search_engine.search_similar(query_vector, k, **options)+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="FAISSAdapter",+ message=f"Searching for {k} similar vectors"+ )++ try:+ if self.search_engine is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Index not initialized")+ raise ProcessingError("Index not initialized. Call create_index() first.")++ self.progress_tracker.update_tracking(tracking_id, message="Performing similarity search...")+ results = self.search_engine.search_similar(query_vector, k, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Found {len(results)} similar vectors")+ return results+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef save_index(self, path: Union[str, Path], **options) -> bool:"""diff --git a/semantica/vector_store/hybrid_search.py b/semantica/vector_store/hybrid_search.pyindex a470aeea..3c0c1e0e 100644--- a/semantica/vector_store/hybrid_search.py+++ b/semantica/vector_store/hybrid_search.py@@ -40,6 +40,7 @@ import numpy as npfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerclass MetadataFilter:@@ -279,6 +280,7 @@ class HybridSearch:"""Initialize hybrid search."""self.logger = get_logger("hybrid_search")self.config = config+ self.progress_tracker = get_progress_tracker()self.ranker = SearchRanker(config.get("ranking_strategy", "reciprocal_rank_fusion"))def search(@@ -306,45 +308,62 @@ class HybridSearch:Returns:List of search results"""- if not vectors or not metadata:- return []-- # Filter by metadata first- if metadata_filter:- filtered_indices = [- i for i, meta in enumerate(metadata)- if metadata_filter.matches(meta)- ]-- filtered_vectors = [vectors[i] for i in filtered_indices]- filtered_metadata = [metadata[i] for i in filtered_indices]- filtered_ids = [vector_ids[i] for i in filtered_indices]- else:- filtered_vectors = vectors- filtered_metadata = metadata- filtered_ids = vector_ids-- if not filtered_vectors:- return []-- # Perform vector similarity search- vector_results = self._vector_search(- query_vector,- filtered_vectors,- filtered_ids,- k * 2, # Get more results for ranking- **options+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="HybridSearch",+ message=f"Performing hybrid search for {k} results")- # Add metadata to results- for result in vector_results:- result_id = result.get("id")- if result_id in filtered_ids:- idx = filtered_ids.index(result_id)- result["metadata"] = filtered_metadata[idx]-- # Rank and return top k- return vector_results[:k]+ try:+ if not vectors or not metadata:+ self.progress_tracker.stop_tracking(tracking_id, status="completed", message="No vectors or metadata to search")+ return []++ # Filter by metadata first+ if metadata_filter:+ self.progress_tracker.update_tracking(tracking_id, message="Filtering by metadata...")+ filtered_indices = [+ i for i, meta in enumerate(metadata)+ if metadata_filter.matches(meta)+ ]++ filtered_vectors = [vectors[i] for i in filtered_indices]+ filtered_metadata = [metadata[i] for i in filtered_indices]+ filtered_ids = [vector_ids[i] for i in filtered_indices]+ else:+ filtered_vectors = vectors+ filtered_metadata = metadata+ filtered_ids = vector_ids++ if not filtered_vectors:+ self.progress_tracker.stop_tracking(tracking_id, status="completed", message="No vectors after filtering")+ return []++ # Perform vector similarity search+ self.progress_tracker.update_tracking(tracking_id, message="Performing vector similarity search...")+ vector_results = self._vector_search(+ query_vector,+ filtered_vectors,+ filtered_ids,+ k * 2, # Get more results for ranking+ **options+ )++ # Add metadata to results+ self.progress_tracker.update_tracking(tracking_id, message="Adding metadata to results...")+ for result in vector_results:+ result_id = result.get("id")+ if result_id in filtered_ids:+ idx = filtered_ids.index(result_id)+ result["metadata"] = filtered_metadata[idx]++ # Rank and return top k+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Hybrid search completed: {len(vector_results[:k])} results")+ return vector_results[:k]+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef _vector_search(self,diff --git a/semantica/vector_store/metadata_store.py b/semantica/vector_store/metadata_store.pyindex 03c8a23d..c114e920 100644--- a/semantica/vector_store/metadata_store.py+++ b/semantica/vector_store/metadata_store.py@@ -41,6 +41,7 @@ import jsonfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerclass MetadataIndex:@@ -187,6 +188,7 @@ class MetadataStore:"""Initialize metadata store."""self.logger = get_logger("metadata_store")self.config = config+ self.progress_tracker = get_progress_tracker()self.schema = MetadataSchema(schema)self.index = MetadataIndex()self.metadata: Dict[str, Dict[str, Any]] = {}@@ -208,18 +210,29 @@ class MetadataStore:Returns:True if successful"""+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="MetadataStore",+ message=f"Storing metadata for vector {vector_id}"+ )+try:# Validate against schema+ self.progress_tracker.update_tracking(tracking_id, message="Validating metadata against schema...")self.schema.validate(metadata)# Store metadata+ self.progress_tracker.update_tracking(tracking_id, message="Indexing metadata...")self.metadata[vector_id] = metadataself.index.index_metadata(vector_id, metadata)self.logger.debug(f"Stored metadata for vector {vector_id}")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Metadata stored for vector {vector_id}")return Trueexcept Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Failed to store metadata: {str(e)}")def get_metadata(self, vector_id: str) -> Optional[Dict[str, Any]]:diff --git a/semantica/vector_store/milvus_adapter.py b/semantica/vector_store/milvus_adapter.pyindex 5bc17c88..e4273b7b 100644--- a/semantica/vector_store/milvus_adapter.py+++ b/semantica/vector_store/milvus_adapter.py@@ -40,6 +40,7 @@ import numpy as npfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker# Optional Milvus importtry:@@ -255,6 +256,7 @@ class MilvusAdapter:"""Initialize Milvus adapter."""self.logger = get_logger("milvus_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.host = host or config.get("host", "localhost")self.port = port or config.get("port", 19530)self.user = user or config.get("user")@@ -407,14 +409,25 @@ class MilvusAdapter:Returns:Insert result"""- if self.collection is None:- raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")-- if not MILVUS_AVAILABLE:- raise ProcessingError("Milvus not available")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="MilvusAdapter",+ message=f"Inserting {len(vectors)} vectors into Milvus collection"+ )try:+ if self.collection is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Collection not initialized")+ raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")++ if not MILVUS_AVAILABLE:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Milvus not available")+ raise ProcessingError("Milvus not available")+# Convert vectors to list format+ self.progress_tracker.update_tracking(tracking_id, message="Converting vectors to list format...")vector_data = []for vector in vectors:if isinstance(vector, np.ndarray):@@ -422,9 +435,15 @@ class MilvusAdapter:vector_data.append(vector)data = [vector_data]- return self.collection.insert(data, **options)+ self.progress_tracker.update_tracking(tracking_id, message="Inserting vectors into collection...")+ result = self.collection.insert(data, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Inserted {len(vectors)} vectors")+ return resultexcept Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Failed to insert vectors: {str(e)}")def search_vectors(@@ -448,16 +467,34 @@ class MilvusAdapter:Returns:List of search results"""- if self.search_engine is None:- raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")-- # Load collection if not loaded- if not self.collection.collection.has_index():- self.collection.load()-- return self.search_engine.similarity_search(- query_vector, limit, metric_type, expr, **options+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="MilvusAdapter",+ message=f"Searching for {limit} similar vectors in Milvus")++ try:+ if self.search_engine is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Collection not initialized")+ raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")++ # Load collection if not loaded+ if not self.collection.collection.has_index():+ self.progress_tracker.update_tracking(tracking_id, message="Loading collection...")+ self.collection.load()++ self.progress_tracker.update_tracking(tracking_id, message="Performing similarity search...")+ results = self.search_engine.similarity_search(+ query_vector, limit, metric_type, expr, **options+ )++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Found {len(results)} similar vectors")+ return results+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef get_stats(self, collection_name: Optional[str] = None) -> Dict[str, Any]:"""Get collection statistics."""diff --git a/semantica/vector_store/namespace_manager.py b/semantica/vector_store/namespace_manager.pyindex 53af4a4e..5edfcb2a 100644--- a/semantica/vector_store/namespace_manager.py+++ b/semantica/vector_store/namespace_manager.py@@ -40,6 +40,7 @@ from datetime import datetimefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerclass Namespace:@@ -126,6 +127,7 @@ class NamespaceManager:"""Initialize namespace manager."""self.logger = get_logger("namespace_manager")self.config = config+ self.progress_tracker = get_progress_tracker()self.namespaces: Dict[str, Namespace] = {}self.default_namespace = config.get("default_namespace", "default")self.vector_namespace_map: Dict[str, str] = {} # vector_id -> namespace@@ -149,17 +151,34 @@ class NamespaceManager:Returns:Namespace instance"""- if name in self.namespaces:- raise ValidationError(f"Namespace '{name}' already exists")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message=f"Creating namespace: {name}"+ )- if not self._validate_namespace_name(name):- raise ValidationError(f"Invalid namespace name: {name}")-- namespace = Namespace(name, description, metadata, **options)- self.namespaces[name] = namespace-- self.logger.info(f"Created namespace: {name}")- return namespace+ try:+ if name in self.namespaces:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message=f"Namespace '{name}' already exists")+ raise ValidationError(f"Namespace '{name}' already exists")++ if not self._validate_namespace_name(name):+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message=f"Invalid namespace name: {name}")+ raise ValidationError(f"Invalid namespace name: {name}")++ self.progress_tracker.update_tracking(tracking_id, message="Initializing namespace...")+ namespace = Namespace(name, description, metadata, **options)+ self.namespaces[name] = namespace++ self.logger.info(f"Created namespace: {name}")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Namespace '{name}' created successfully")+ return namespace+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef get_namespace(self, name: str) -> Optional[Namespace]:"""@@ -184,20 +203,37 @@ class NamespaceManager:Returns:True if successful"""- if name not in self.namespaces:- raise ProcessingError(f"Namespace '{name}' does not exist")-- if name == self.default_namespace:- raise ProcessingError("Cannot delete default namespace")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message=f"Deleting namespace: {name}"+ )- # Remove namespace vectors from mapping- namespace = self.namespaces[name]- for vector_id in list(namespace.vector_ids):- self.vector_namespace_map.pop(vector_id, None)-- del self.namespaces[name]- self.logger.info(f"Deleted namespace: {name}")- return True+ try:+ if name not in self.namespaces:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message=f"Namespace '{name}' does not exist")+ raise ProcessingError(f"Namespace '{name}' does not exist")++ if name == self.default_namespace:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Cannot delete default namespace")+ raise ProcessingError("Cannot delete default namespace")++ # Remove namespace vectors from mapping+ self.progress_tracker.update_tracking(tracking_id, message="Removing vectors from namespace mapping...")+ namespace = self.namespaces[name]+ for vector_id in list(namespace.vector_ids):+ self.vector_namespace_map.pop(vector_id, None)++ del self.namespaces[name]+ self.logger.info(f"Deleted namespace: {name}")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Namespace '{name}' deleted successfully")+ return True+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef list_namespaces(self, **options) -> List[str]:"""@@ -209,7 +245,20 @@ class NamespaceManager:Returns:List of namespace names"""- return list(self.namespaces.keys())+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message="Listing all namespaces"+ )++ try:+ namespaces = list(self.namespaces.keys())+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Found {len(namespaces)} namespaces")+ return namespaces+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef add_vector_to_namespace(self,@@ -228,20 +277,36 @@ class NamespaceManager:Returns:True if successful"""- if namespace not in self.namespaces:- raise ProcessingError(f"Namespace '{namespace}' does not exist")-- # Remove from old namespace if exists- old_namespace = self.vector_namespace_map.get(vector_id)- if old_namespace and old_namespace in self.namespaces:- self.namespaces[old_namespace].remove_vector(vector_id)-- # Add to new namespace- self.namespaces[namespace].add_vector(vector_id)- self.vector_namespace_map[vector_id] = namespace+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message=f"Adding vector {vector_id} to namespace {namespace}"+ )- self.logger.debug(f"Added vector {vector_id} to namespace {namespace}")- return True+ try:+ if namespace not in self.namespaces:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message=f"Namespace '{namespace}' does not exist")+ raise ProcessingError(f"Namespace '{namespace}' does not exist")++ # Remove from old namespace if exists+ old_namespace = self.vector_namespace_map.get(vector_id)+ if old_namespace and old_namespace in self.namespaces:+ self.progress_tracker.update_tracking(tracking_id, message=f"Removing from old namespace: {old_namespace}")+ self.namespaces[old_namespace].remove_vector(vector_id)++ # Add to new namespace+ self.progress_tracker.update_tracking(tracking_id, message=f"Adding to namespace: {namespace}")+ self.namespaces[namespace].add_vector(vector_id)+ self.vector_namespace_map[vector_id] = namespace++ self.logger.debug(f"Added vector {vector_id} to namespace {namespace}")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Vector {vector_id} added to namespace {namespace}")+ return True+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef remove_vector_from_namespace(self,@@ -260,15 +325,30 @@ class NamespaceManager:Returns:True if successful"""- if namespace is None:- namespace = self.vector_namespace_map.get(vector_id)+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message=f"Removing vector {vector_id} from namespace"+ )- if namespace and namespace in self.namespaces:- self.namespaces[namespace].remove_vector(vector_id)- self.vector_namespace_map.pop(vector_id, None)- return True-- return False+ try:+ if namespace is None:+ namespace = self.vector_namespace_map.get(vector_id)++ if namespace and namespace in self.namespaces:+ self.progress_tracker.update_tracking(tracking_id, message=f"Removing from namespace: {namespace}")+ self.namespaces[namespace].remove_vector(vector_id)+ self.vector_namespace_map.pop(vector_id, None)+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Vector {vector_id} removed from namespace {namespace}")+ return True++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Vector {vector_id} not found in any namespace")+ return False+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef get_vector_namespace(self, vector_id: str) -> Optional[str]:"""@@ -292,10 +372,25 @@ class NamespaceManager:Returns:List of vector IDs"""- if namespace not in self.namespaces:- return []+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message=f"Getting vectors from namespace: {namespace}"+ )- return list(self.namespaces[namespace].vector_ids)+ try:+ if namespace not in self.namespaces:+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Namespace '{namespace}' not found")+ return []++ vectors = list(self.namespaces[namespace].vector_ids)+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Found {len(vectors)} vectors in namespace {namespace}")+ return vectors+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef set_namespace_access_control(self,@@ -354,18 +449,34 @@ class NamespaceManager:Returns:Namespace statistics"""- if namespace not in self.namespaces:- raise ProcessingError(f"Namespace '{namespace}' does not exist")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="NamespaceManager",+ message=f"Getting statistics for namespace: {namespace}"+ )- ns = self.namespaces[namespace]- return {- "name": ns.name,- "description": ns.description,- "vector_count": ns.get_vector_count(),- "created_at": ns.created_at.isoformat(),- "updated_at": ns.updated_at.isoformat(),- "metadata": ns.metadata- }+ try:+ if namespace not in self.namespaces:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message=f"Namespace '{namespace}' does not exist")+ raise ProcessingError(f"Namespace '{namespace}' does not exist")++ self.progress_tracker.update_tracking(tracking_id, message="Collecting namespace statistics...")+ ns = self.namespaces[namespace]+ stats = {+ "name": ns.name,+ "description": ns.description,+ "vector_count": ns.get_vector_count(),+ "created_at": ns.created_at.isoformat(),+ "updated_at": ns.updated_at.isoformat(),+ "metadata": ns.metadata+ }+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Statistics collected for namespace {namespace}")+ return stats+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef get_all_stats(self) -> Dict[str, Dict[str, Any]]:"""Get statistics for all namespaces."""diff --git a/semantica/vector_store/pinecone_adapter.py b/semantica/vector_store/pinecone_adapter.pyindex 2465ff05..f5dd01f5 100644--- a/semantica/vector_store/pinecone_adapter.py+++ b/semantica/vector_store/pinecone_adapter.py@@ -38,6 +38,7 @@ import numpy as npfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker# Optional Pinecone importtry:@@ -228,6 +229,7 @@ class PineconeAdapter:"""Initialize Pinecone adapter."""self.logger = get_logger("pinecone_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.api_key = api_key or config.get("api_key")self.environment = environment or config.get("environment")@@ -366,23 +368,41 @@ class PineconeAdapter:Returns:Upsert response"""- if self.index is None:- raise ProcessingError("Index not initialized. Call create_index() or get_index() first.")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="PineconeAdapter",+ message=f"Upserting {len(vectors)} vectors to Pinecone"+ )- # Format vectors- formatted_vectors = []- for i, vector in enumerate(vectors):- if isinstance(vector, np.ndarray):- vector = vector.tolist()+ try:+ if self.index is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Index not initialized")+ raise ProcessingError("Index not initialized. Call create_index() or get_index() first.")- vector_data = {"id": ids[i], "values": vector}+ # Format vectors+ self.progress_tracker.update_tracking(tracking_id, message="Formatting vectors...")+ formatted_vectors = []+ for i, vector in enumerate(vectors):+ if isinstance(vector, np.ndarray):+ vector = vector.tolist()++ vector_data = {"id": ids[i], "values": vector}++ if metadata and i < len(metadata):+ vector_data["metadata"] = PineconeMetadata.validate_metadata(metadata[i])++ formatted_vectors.append(vector_data)- if metadata and i < len(metadata):- vector_data["metadata"] = PineconeMetadata.validate_metadata(metadata[i])+ self.progress_tracker.update_tracking(tracking_id, message="Upserting vectors to Pinecone...")+ result = self.index.upsert_vectors(formatted_vectors, namespace, **options)- formatted_vectors.append(vector_data)-- return self.index.upsert_vectors(formatted_vectors, namespace, **options)+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Upserted {len(vectors)} vectors")+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef query_vectors(self,@@ -405,14 +425,32 @@ class PineconeAdapter:Returns:List of search results"""- if self.query_builder is None:- raise ProcessingError("Index not initialized. Call create_index() or get_index() first.")-- query_params = self.query_builder.build_query(- query_vector, top_k, namespace, filter, **options+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="PineconeAdapter",+ message=f"Querying {top_k} similar vectors from Pinecone")- return self.query_builder.execute(query_params)+ try:+ if self.query_builder is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Index not initialized")+ raise ProcessingError("Index not initialized. Call create_index() or get_index() first.")++ self.progress_tracker.update_tracking(tracking_id, message="Building query...")+ query_params = self.query_builder.build_query(+ query_vector, top_k, namespace, filter, **options+ )++ self.progress_tracker.update_tracking(tracking_id, message="Executing query...")+ results = self.query_builder.execute(query_params)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Query completed: {len(results) if isinstance(results, list) else 'N/A'} results")+ return results+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef delete_vectors(self,diff --git a/semantica/vector_store/qdrant_adapter.py b/semantica/vector_store/qdrant_adapter.pyindex 68d47408..b6ddef7c 100644--- a/semantica/vector_store/qdrant_adapter.py+++ b/semantica/vector_store/qdrant_adapter.py@@ -38,6 +38,7 @@ import numpy as npfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker# Optional Qdrant importtry:@@ -250,6 +251,7 @@ class QdrantAdapter:"""Initialize Qdrant adapter."""self.logger = get_logger("qdrant_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.url = url or config.get("url", "http://localhost:6333")self.api_key = api_key or config.get("api_key")@@ -377,13 +379,24 @@ class QdrantAdapter:Returns:Insert response"""- if self.collection is None:- raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")-- if not QDRANT_AVAILABLE:- raise ProcessingError("Qdrant not available")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="QdrantAdapter",+ message=f"Inserting {len(vectors)} vectors into Qdrant collection"+ )try:+ if self.collection is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Collection not initialized")+ raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")++ if not QDRANT_AVAILABLE:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Qdrant not available")+ raise ProcessingError("Qdrant not available")++ self.progress_tracker.update_tracking(tracking_id, message="Preparing points...")points = []for i, (vector, point_id) in enumerate(zip(vectors, ids)):if isinstance(vector, np.ndarray):@@ -399,9 +412,15 @@ class QdrantAdapter:))- return self.collection.upsert_points(points, **options)+ self.progress_tracker.update_tracking(tracking_id, message="Upserting points to collection...")+ result = self.collection.upsert_points(points, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Inserted {len(vectors)} vectors")+ return resultexcept Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Failed to insert vectors: {str(e)}")def search_vectors(@@ -423,10 +442,27 @@ class QdrantAdapter:Returns:List of search results"""- if self.search_engine is None:- raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="QdrantAdapter",+ message=f"Searching for {limit} similar vectors in Qdrant"+ )- return self.search_engine.similarity_search(query_vector, limit, filter, **options)+ try:+ if self.search_engine is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Collection not initialized")+ raise ProcessingError("Collection not initialized. Call create_collection() or get_collection() first.")++ self.progress_tracker.update_tracking(tracking_id, message="Performing similarity search...")+ results = self.search_engine.similarity_search(query_vector, limit, filter, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Found {len(results)} similar vectors")+ return results+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef delete_vectors(self,diff --git a/semantica/vector_store/vector_store.py b/semantica/vector_store/vector_store.pyindex 18c375e5..3cfe2be6 100644--- a/semantica/vector_store/vector_store.py+++ b/semantica/vector_store/vector_store.py@@ -42,6 +42,7 @@ import numpy as npfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerclass VectorStore:@@ -61,11 +62,12 @@ class VectorStore:self.logger = get_logger("vector_store")self.config = config or {}self.config.update(kwargs)+ self.progress_tracker = get_progress_tracker()self.backend = backendself.vectors: Dict[str, np.ndarray] = {}self.metadata: Dict[str, Dict[str, Any]] = {}- self.dimension = config.get("dimension", 768)+ self.dimension = config.get("dimension", 768) if config else 768# Initialize backend-specific indexerself.indexer = VectorIndexer(backend=backend, dimension=self.dimension, **config)@@ -88,19 +90,33 @@ class VectorStore:Returns:List of vector IDs"""- vector_ids = []- metadata = metadata or [{}] * len(vectors)-- for i, (vector, meta) in enumerate(zip(vectors, metadata)):- vector_id = f"vec_{len(self.vectors) + i}"- self.vectors[vector_id] = vector- self.metadata[vector_id] = meta- vector_ids.append(vector_id)-- # Update index- self.indexer.create_index(list(self.vectors.values()), vector_ids)+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="VectorStore",+ message=f"Storing {len(vectors)} vectors"+ )- return vector_ids+ try:+ vector_ids = []+ metadata = metadata or [{}] * len(vectors)++ self.progress_tracker.update_tracking(tracking_id, message="Storing vectors...")+ for i, (vector, meta) in enumerate(zip(vectors, metadata)):+ vector_id = f"vec_{len(self.vectors) + i}"+ self.vectors[vector_id] = vector+ self.metadata[vector_id] = meta+ vector_ids.append(vector_id)++ # Update index+ self.progress_tracker.update_tracking(tracking_id, message="Updating vector index...")+ self.indexer.create_index(list(self.vectors.values()), vector_ids)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Stored {len(vector_ids)} vectors")+ return vector_ids+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef search_vectors(self,@@ -119,19 +135,33 @@ class VectorStore:Returns:List of search results with scores"""- if not self.vectors:- return []-- # Use retriever for similarity search- results = self.retriever.search_similar(- query_vector,- list(self.vectors.values()),- list(self.vectors.keys()),- k=k,- **options+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="VectorStore",+ message=f"Searching for {k} similar vectors")- return results+ try:+ if not self.vectors:+ self.progress_tracker.stop_tracking(tracking_id, status="completed", message="No vectors to search")+ return []++ # Use retriever for similarity search+ self.progress_tracker.update_tracking(tracking_id, message="Performing similarity search...")+ results = self.retriever.search_similar(+ query_vector,+ list(self.vectors.values()),+ list(self.vectors.keys()),+ k=k,+ **options+ )++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Found {len(results)} similar vectors")+ return results+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef update_vectors(self,diff --git a/semantica/vector_store/weaviate_adapter.py b/semantica/vector_store/weaviate_adapter.pyindex 34994060..ce6d6b7d 100644--- a/semantica/vector_store/weaviate_adapter.py+++ b/semantica/vector_store/weaviate_adapter.py@@ -39,6 +39,7 @@ import numpy as npfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker# Optional Weaviate importtry:@@ -233,6 +234,7 @@ class WeaviateAdapter:"""Initialize Weaviate adapter."""self.logger = get_logger("weaviate_adapter")self.config = config+ self.progress_tracker = get_progress_tracker()self.url = url or config.get("url", "http://localhost:8080")self.api_key = api_key or config.get("api_key")@@ -361,16 +363,28 @@ class WeaviateAdapter:Returns:List of object IDs"""- if self.collection is None and class_name:- self.get_collection(class_name)-- if self.collection is None:- raise ProcessingError("Collection not initialized. Call get_collection() first.")-- if not WEAVIATE_AVAILABLE:- raise ProcessingError("Weaviate not available")+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="WeaviateAdapter",+ message=f"Adding {len(objects)} objects to Weaviate"+ )try:+ if self.collection is None and class_name:+ self.progress_tracker.update_tracking(tracking_id, message="Getting collection...")+ self.get_collection(class_name)++ if self.collection is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Collection not initialized")+ raise ProcessingError("Collection not initialized. Call get_collection() first.")++ if not WEAVIATE_AVAILABLE:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Weaviate not available")+ raise ProcessingError("Weaviate not available")++ self.progress_tracker.update_tracking(tracking_id, message="Adding objects in batch...")object_ids = []with self.collection.batch.dynamic() as batch:@@ -384,9 +398,12 @@ class WeaviateAdapter:object_ids.append(str(uuid))self.logger.info(f"Added {len(objects)} objects to Weaviate")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Added {len(objects)} objects to Weaviate")return object_idsexcept Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))raise ProcessingError(f"Failed to add objects: {str(e)}")def query_vectors(@@ -410,13 +427,31 @@ class WeaviateAdapter:Returns:List of search results"""- if self.collection is None and class_name:- self.get_collection(class_name)+ tracking_id = self.progress_tracker.start_tracking(+ module="vector_store",+ submodule="WeaviateAdapter",+ message=f"Querying {limit} similar vectors from Weaviate"+ )- if self.query_builder is None:- raise ProcessingError("Collection not initialized. Call get_collection() first.")-- return self.query_builder.similarity_search(query_vector, limit, where, **options)+ try:+ if self.collection is None and class_name:+ self.progress_tracker.update_tracking(tracking_id, message="Getting collection...")+ self.get_collection(class_name)++ if self.query_builder is None:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Collection not initialized")+ raise ProcessingError("Collection not initialized. Call get_collection() first.")++ self.progress_tracker.update_tracking(tracking_id, message="Performing similarity search...")+ results = self.query_builder.similarity_search(query_vector, limit, where, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Query completed: {len(results)} results")+ return results+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef graphql_query(self, query: str, **options) -> Dict[str, Any]:"""diff --git a/semantica/visualization/analytics_visualizer.py b/semantica/visualization/analytics_visualizer.pyindex 1cb3d900..716644b9 100644--- a/semantica/visualization/analytics_visualizer.py+++ b/semantica/visualization/analytics_visualizer.py@@ -41,6 +41,7 @@ from plotly.subplots import make_subplotsfrom ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.color_schemes import ColorPalette, ColorSchemefrom .utils.export_formats import export_plotly_figure@@ -60,6 +61,7 @@ class AnalyticsVisualizer:"""Initialize analytics visualizer."""self.logger = get_logger("analytics_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()color_scheme_name = config.get("color_scheme", "default")try:self.color_scheme = ColorScheme[color_scheme_name.upper()]@@ -89,44 +91,60 @@ class AnalyticsVisualizer:Returns:Visualization figure or None"""- self.logger.info(f"Visualizing {centrality_type} centrality rankings")-- # Get rankings- rankings = centrality.get("rankings", [])- if not rankings:- # Try to get from centrality scores- centrality_scores = centrality.get("centrality", {})- rankings = [{"node": node, "score": score} for node, score in centrality_scores.items()]- rankings.sort(key=lambda x: x["score"], reverse=True)-- # Get top N- top_rankings = rankings[:top_n]-- nodes = [r["node"] for r in top_rankings]- scores = [r["score"] for r in top_rankings]-- fig = go.Figure(data=[go.Bar(- x=nodes,- y=scores,- marker_color='lightblue',- text=[f"{s:.3f}" for s in scores],- textposition='auto'- )])-- fig.update_layout(- title=f"Top {top_n} Nodes by {centrality_type.capitalize()} Centrality",- xaxis_title="Node",- yaxis_title="Centrality Score",- xaxis={'tickangle': -45},- width=1000,- height=600+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="AnalyticsVisualizer",+ message=f"Visualizing {centrality_type} centrality rankings")- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None+ try:+ self.logger.info(f"Visualizing {centrality_type} centrality rankings")++ # Get rankings+ self.progress_tracker.update_tracking(tracking_id, message="Processing centrality data...")+ rankings = centrality.get("rankings", [])+ if not rankings:+ # Try to get from centrality scores+ centrality_scores = centrality.get("centrality", {})+ rankings = [{"node": node, "score": score} for node, score in centrality_scores.items()]+ rankings.sort(key=lambda x: x["score"], reverse=True)++ # Get top N+ top_rankings = rankings[:top_n]++ nodes = [r["node"] for r in top_rankings]+ scores = [r["score"] for r in top_rankings]++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ fig = go.Figure(data=[go.Bar(+ x=nodes,+ y=scores,+ marker_color='lightblue',+ text=[f"{s:.3f}" for s in scores],+ textposition='auto'+ )])++ fig.update_layout(+ title=f"Top {top_n} Nodes by {centrality_type.capitalize()} Centrality",+ xaxis_title="Node",+ yaxis_title="Centrality Score",+ xaxis={'tickangle': -45},+ width=1000,+ height=600+ )++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Centrality rankings visualization generated: top {top_n} nodes")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Centrality rankings saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_community_structure(self,diff --git a/semantica/visualization/embedding_visualizer.py b/semantica/visualization/embedding_visualizer.pyindex cfe0dc9c..6e35dc8b 100644--- a/semantica/visualization/embedding_visualizer.py+++ b/semantica/visualization/embedding_visualizer.py@@ -49,6 +49,7 @@ except ImportError:from ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.color_schemes import ColorPalette, ColorSchemefrom .utils.export_formats import export_plotly_figure, export_matplotlib_figure@@ -75,6 +76,7 @@ class EmbeddingVisualizer:"""self.logger = get_logger("embedding_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()color_scheme_name = config.get("color_scheme", "default")try:@@ -109,15 +111,32 @@ class EmbeddingVisualizer:Returns:Visualization figure or None"""- self.logger.info(f"Visualizing 2D projection using {method}")-- if embeddings.shape[1] <= 2:- # Already 2D or less, use directly- projected = embeddings[:, :2]- else:- projected = self._reduce_dimensions(embeddings, method=method, n_components=2, **options)+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="EmbeddingVisualizer",+ message=f"Visualizing 2D projection using {method}"+ )- return self._visualize_2d_plotly(projected, labels, output, file_path, **options)+ try:+ self.logger.info(f"Visualizing 2D projection using {method}")++ if embeddings.shape[1] <= 2:+ # Already 2D or less, use directly+ self.progress_tracker.update_tracking(tracking_id, message="Using embeddings directly (already 2D)...")+ projected = embeddings[:, :2]+ else:+ self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ projected = self._reduce_dimensions(embeddings, method=method, n_components=2, **options)++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ result = self._visualize_2d_plotly(projected, labels, output, file_path, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"2D projection visualization generated: {len(projected)} points")+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_3d_projection(self,@@ -142,14 +161,31 @@ class EmbeddingVisualizer:Returns:Visualization figure or None"""- self.logger.info(f"Visualizing 3D projection using {method}")-- if embeddings.shape[1] <= 3:- projected = embeddings[:, :3]- else:- projected = self._reduce_dimensions(embeddings, method=method, n_components=3, **options)+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="EmbeddingVisualizer",+ message=f"Visualizing 3D projection using {method}"+ )- return self._visualize_3d_plotly(projected, labels, output, file_path, **options)+ try:+ self.logger.info(f"Visualizing 3D projection using {method}")++ if embeddings.shape[1] <= 3:+ self.progress_tracker.update_tracking(tracking_id, message="Using embeddings directly (already 3D)...")+ projected = embeddings[:, :3]+ else:+ self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ projected = self._reduce_dimensions(embeddings, method=method, n_components=3, **options)++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ result = self._visualize_3d_plotly(projected, labels, output, file_path, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"3D projection visualization generated: {len(projected)} points")+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_similarity_heatmap(self,@@ -172,44 +208,60 @@ class EmbeddingVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing similarity heatmap")-- # Calculate cosine similarity- # Normalize embeddings- norms = np.linalg.norm(embeddings, axis=1, keepdims=True)- norms[norms == 0] = 1 # Avoid division by zero- normalized = embeddings / norms-- # Calculate similarity matrix- similarity_matrix = np.dot(normalized, normalized.T)-- fig = go.Figure(data=go.Heatmap(- z=similarity_matrix,- colorscale='Viridis',- text=similarity_matrix,- texttemplate='%{text:.2f}',- textfont={"size": 8}- ))+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="EmbeddingVisualizer",+ message="Visualizing similarity heatmap"+ )- if labels:+ try:+ self.logger.info("Visualizing similarity heatmap")++ # Calculate cosine similarity+ self.progress_tracker.update_tracking(tracking_id, message="Calculating similarity matrix...")+ # Normalize embeddings+ norms = np.linalg.norm(embeddings, axis=1, keepdims=True)+ norms[norms == 0] = 1 # Avoid division by zero+ normalized = embeddings / norms++ # Calculate similarity matrix+ similarity_matrix = np.dot(normalized, normalized.T)++ self.progress_tracker.update_tracking(tracking_id, message="Generating heatmap visualization...")+ fig = go.Figure(data=go.Heatmap(+ z=similarity_matrix,+ colorscale='Viridis',+ text=similarity_matrix,+ texttemplate='%{text:.2f}',+ textfont={"size": 8}+ ))++ if labels:+ fig.update_layout(+ xaxis=dict(tickmode='array', tickvals=list(range(len(labels))), ticktext=labels),+ yaxis=dict(tickmode='array', tickvals=list(range(len(labels))), ticktext=labels)+ )+fig.update_layout(- xaxis=dict(tickmode='array', tickvals=list(range(len(labels))), ticktext=labels),- yaxis=dict(tickmode='array', tickvals=list(range(len(labels))), ticktext=labels)+ title="Embedding Similarity Heatmap",+ xaxis_title="Embedding Index",+ yaxis_title="Embedding Index",+ width=800,+ height=800)-- fig.update_layout(- title="Embedding Similarity Heatmap",- xaxis_title="Embedding Index",- yaxis_title="Embedding Index",- width=800,- height=800- )-- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Similarity heatmap generated: {len(embeddings)}x{len(embeddings)} matrix")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Similarity heatmap saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_clustering(self,@@ -234,45 +286,62 @@ class EmbeddingVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing embedding clusters")-- # Project to 2D- if embeddings.shape[1] <= 2:- projected = embeddings[:, :2]- else:- projected = self._reduce_dimensions(embeddings, method=method, n_components=2, **options)-- num_clusters = len(set(cluster_labels))- cluster_colors = ColorPalette.get_community_colors(num_clusters, self.color_scheme)-- colors = [cluster_colors[label % num_clusters] for label in cluster_labels]-- fig = go.Figure(data=go.Scatter(- x=projected[:, 0],- y=projected[:, 1],- mode='markers',- marker=dict(- size=self.point_size,- color=colors,- line=dict(width=1, color='black')- ),- text=[f"Cluster {label}" for label in cluster_labels],- hovertemplate='%{text}<extra></extra>'- ))-- fig.update_layout(- title="Embedding Clusters",- xaxis_title="Dimension 1",- yaxis_title="Dimension 2",- width=800,- height=600+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="EmbeddingVisualizer",+ message="Visualizing embedding clusters")- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None+ try:+ self.logger.info("Visualizing embedding clusters")++ # Project to 2D+ if embeddings.shape[1] <= 2:+ self.progress_tracker.update_tracking(tracking_id, message="Using embeddings directly (already 2D)...")+ projected = embeddings[:, :2]+ else:+ self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ projected = self._reduce_dimensions(embeddings, method=method, n_components=2, **options)++ num_clusters = len(set(cluster_labels))+ cluster_colors = ColorPalette.get_community_colors(num_clusters, self.color_scheme)++ colors = [cluster_colors[label % num_clusters] for label in cluster_labels]++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ fig = go.Figure(data=go.Scatter(+ x=projected[:, 0],+ y=projected[:, 1],+ mode='markers',+ marker=dict(+ size=self.point_size,+ color=colors,+ line=dict(width=1, color='black')+ ),+ text=[f"Cluster {label}" for label in cluster_labels],+ hovertemplate='%{text}<extra></extra>'+ ))++ fig.update_layout(+ title="Embedding Clusters",+ xaxis_title="Dimension 1",+ yaxis_title="Dimension 2",+ width=800,+ height=600+ )++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Clustering visualization generated: {num_clusters} clusters, {len(embeddings)} points")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Clustering visualization saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_multimodal_comparison(self,@@ -299,70 +368,90 @@ class EmbeddingVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing multi-modal embedding comparison")-- # Collect embeddings and labels- all_embeddings = []- all_labels = []- all_types = []-- if text_embeddings is not None:- all_embeddings.append(text_embeddings)- all_labels.extend([f"Text {i}" for i in range(len(text_embeddings))])- all_types.extend(["text"] * len(text_embeddings))-- if image_embeddings is not None:- all_embeddings.append(image_embeddings)- all_labels.extend([f"Image {i}" for i in range(len(image_embeddings))])- all_types.extend(["image"] * len(image_embeddings))-- if audio_embeddings is not None:- all_embeddings.append(audio_embeddings)- all_labels.extend([f"Audio {i}" for i in range(len(audio_embeddings))])- all_types.extend(["audio"] * len(audio_embeddings))-- if not all_embeddings:- raise ProcessingError("No embeddings provided")-- # Concatenate embeddings- combined_embeddings = np.vstack(all_embeddings)-- # Project to 2D- if combined_embeddings.shape[1] <= 2:- projected = combined_embeddings[:, :2]- else:- projected = self._reduce_dimensions(combined_embeddings, method=method, n_components=2, **options)-- # Color by type- type_colors = {"text": "#1f77b4", "image": "#ff7f0e", "audio": "#2ca02c"}- colors = [type_colors.get(t, "#888") for t in all_types]-- fig = go.Figure(data=go.Scatter(- x=projected[:, 0],- y=projected[:, 1],- mode='markers',- marker=dict(- size=self.point_size,- color=colors,- line=dict(width=1, color='black')- ),- text=all_labels,- hovertemplate='%{text}<extra></extra>'- ))-- fig.update_layout(- title="Multi-Modal Embedding Comparison",- xaxis_title="Dimension 1",- yaxis_title="Dimension 2",- width=800,- height=600+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="EmbeddingVisualizer",+ message="Visualizing multi-modal embedding comparison")- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None+ try:+ self.logger.info("Visualizing multi-modal embedding comparison")++ # Collect embeddings and labels+ self.progress_tracker.update_tracking(tracking_id, message="Collecting embeddings...")+ all_embeddings = []+ all_labels = []+ all_types = []++ if text_embeddings is not None:+ all_embeddings.append(text_embeddings)+ all_labels.extend([f"Text {i}" for i in range(len(text_embeddings))])+ all_types.extend(["text"] * len(text_embeddings))++ if image_embeddings is not None:+ all_embeddings.append(image_embeddings)+ all_labels.extend([f"Image {i}" for i in range(len(image_embeddings))])+ all_types.extend(["image"] * len(image_embeddings))++ if audio_embeddings is not None:+ all_embeddings.append(audio_embeddings)+ all_labels.extend([f"Audio {i}" for i in range(len(audio_embeddings))])+ all_types.extend(["audio"] * len(audio_embeddings))++ if not all_embeddings:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="No embeddings provided")+ raise ProcessingError("No embeddings provided")++ # Concatenate embeddings+ combined_embeddings = np.vstack(all_embeddings)++ # Project to 2D+ if combined_embeddings.shape[1] <= 2:+ self.progress_tracker.update_tracking(tracking_id, message="Using embeddings directly (already 2D)...")+ projected = combined_embeddings[:, :2]+ else:+ self.progress_tracker.update_tracking(tracking_id, message=f"Reducing dimensions using {method}...")+ projected = self._reduce_dimensions(combined_embeddings, method=method, n_components=2, **options)++ # Color by type+ type_colors = {"text": "#1f77b4", "image": "#ff7f0e", "audio": "#2ca02c"}+ colors = [type_colors.get(t, "#888") for t in all_types]++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ fig = go.Figure(data=go.Scatter(+ x=projected[:, 0],+ y=projected[:, 1],+ mode='markers',+ marker=dict(+ size=self.point_size,+ color=colors,+ line=dict(width=1, color='black')+ ),+ text=all_labels,+ hovertemplate='%{text}<extra></extra>'+ ))++ fig.update_layout(+ title="Multi-Modal Embedding Comparison",+ xaxis_title="Dimension 1",+ yaxis_title="Dimension 2",+ width=800,+ height=600+ )++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Multi-modal comparison generated: {len(combined_embeddings)} embeddings")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Multi-modal comparison saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_quality_metrics(self,@@ -383,43 +472,59 @@ class EmbeddingVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing embedding quality metrics")-- # Calculate norms- norms = np.linalg.norm(embeddings, axis=1)-- fig = make_subplots(- rows=1, cols=2,- subplot_titles=("Embedding Norm Distribution", "Norm Statistics"),- specs=[[{"type": "histogram"}, {"type": "bar"}]]- )-- # Norm distribution- fig.add_trace(- go.Histogram(x=norms, nbinsx=30, name="Norm Distribution"),- row=1, col=1- )-- # Statistics- stats = {- "Mean": np.mean(norms),- "Std": np.std(norms),- "Min": np.min(norms),- "Max": np.max(norms)- }-- fig.add_trace(- go.Bar(x=list(stats.keys()), y=list(stats.values()), name="Statistics"),- row=1, col=2+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="EmbeddingVisualizer",+ message="Visualizing embedding quality metrics")- fig.update_layout(title="Embedding Quality Metrics")-- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None+ try:+ self.logger.info("Visualizing embedding quality metrics")++ # Calculate norms+ self.progress_tracker.update_tracking(tracking_id, message="Calculating embedding norms...")+ norms = np.linalg.norm(embeddings, axis=1)++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ fig = make_subplots(+ rows=1, cols=2,+ subplot_titles=("Embedding Norm Distribution", "Norm Statistics"),+ specs=[[{"type": "histogram"}, {"type": "bar"}]]+ )++ # Norm distribution+ fig.add_trace(+ go.Histogram(x=norms, nbinsx=30, name="Norm Distribution"),+ row=1, col=1+ )++ # Statistics+ stats = {+ "Mean": np.mean(norms),+ "Std": np.std(norms),+ "Min": np.min(norms),+ "Max": np.max(norms)+ }++ fig.add_trace(+ go.Bar(x=list(stats.keys()), y=list(stats.values()), name="Statistics"),+ row=1, col=2+ )++ fig.update_layout(title="Embedding Quality Metrics")++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Quality metrics visualization generated: {len(embeddings)} embeddings")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Quality metrics saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef _reduce_dimensions(self,diff --git a/semantica/visualization/kg_visualizer.py b/semantica/visualization/kg_visualizer.pyindex 8b7a963e..d014cc53 100644--- a/semantica/visualization/kg_visualizer.py+++ b/semantica/visualization/kg_visualizer.py@@ -42,6 +42,7 @@ import matplotlib.patches as mpatchesfrom ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.layout_algorithms import ForceDirectedLayout, HierarchicalLayout, CircularLayoutfrom .utils.color_schemes import ColorPalette, ColorSchemefrom .utils.export_formats import export_plotly_figure, export_matplotlib_figure, save_html@@ -71,6 +72,7 @@ class KGVisualizer:"""self.logger = get_logger("kg_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()self.layout_type = config.get("layout", "force")color_scheme_name = config.get("color_scheme", "default")@@ -105,20 +107,38 @@ class KGVisualizer:Returns:Plotly figure (if interactive) or None"""- self.logger.info("Visualizing knowledge graph network")-- # Extract entities and relationships- entities = graph.get("entities", [])- relationships = graph.get("relationships", [])-- if not entities:- raise ProcessingError("No entities found in graph")-- # Build node and edge lists- nodes = self._extract_nodes(entities)- edges = self._extract_edges(relationships, entities)+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="KGVisualizer",+ message="Visualizing knowledge graph network"+ )- return self._visualize_network_plotly(nodes, edges, output, file_path, **options)+ try:+ self.logger.info("Visualizing knowledge graph network")++ # Extract entities and relationships+ self.progress_tracker.update_tracking(tracking_id, message="Extracting entities and relationships...")+ entities = graph.get("entities", [])+ relationships = graph.get("relationships", [])++ if not entities:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message="No entities found in graph")+ raise ProcessingError("No entities found in graph")++ # Build node and edge lists+ self.progress_tracker.update_tracking(tracking_id, message="Building node and edge lists...")+ nodes = self._extract_nodes(entities)+ edges = self._extract_edges(relationships, entities)++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ result = self._visualize_network_plotly(nodes, edges, output, file_path, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Visualization generated: {len(nodes)} nodes, {len(edges)} edges")+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_communities(self,diff --git a/semantica/visualization/ontology_visualizer.py b/semantica/visualization/ontology_visualizer.pyindex a9375291..28208923 100644--- a/semantica/visualization/ontology_visualizer.py+++ b/semantica/visualization/ontology_visualizer.py@@ -49,6 +49,7 @@ except ImportError:from ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.layout_algorithms import HierarchicalLayoutfrom .utils.color_schemes import ColorPalette, ColorSchemefrom .utils.export_formats import export_plotly_figure, export_matplotlib_figure, save_html@@ -76,6 +77,7 @@ class OntologyVisualizer:"""self.logger = get_logger("ontology_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()color_scheme_name = config.get("color_scheme", "default")try:@@ -104,35 +106,58 @@ class OntologyVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing ontology class hierarchy")-- # Handle different input formats- if hasattr(ontology, "classes"):- # OntologyGenerator result object- classes = ontology.classes if hasattr(ontology, "classes") else []- elif isinstance(ontology, dict):- classes = ontology.get("classes", ontology.get("class_definitions", []))- else:- classes = []-- # If no classes, try to extract from semantic network- if not classes and isinstance(ontology, dict):- # Check if it's a semantic model or semantic network- semantic_network = ontology.get("semantic_network", ontology.get("network"))- if semantic_network:- classes = self._extract_classes_from_semantic_network(semantic_network)-- if not classes:- raise ProcessingError("No classes found in ontology. Please provide classes or a semantic network.")-- # If output is dot and graphviz is available, use it- if output == "dot" and graphviz is not None and file_path:- return self._visualize_hierarchy_graphviz(classes, file_path, **options)-- # Build hierarchy tree- hierarchy = self._build_hierarchy_tree(classes)+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="OntologyVisualizer",+ message="Visualizing ontology class hierarchy"+ )- return self._visualize_hierarchy_plotly(hierarchy, classes, output, file_path, **options)+ try:+ self.logger.info("Visualizing ontology class hierarchy")++ # Handle different input formats+ self.progress_tracker.update_tracking(tracking_id, message="Extracting classes from ontology...")+ if hasattr(ontology, "classes"):+ # OntologyGenerator result object+ classes = ontology.classes if hasattr(ontology, "classes") else []+ elif isinstance(ontology, dict):+ classes = ontology.get("classes", ontology.get("class_definitions", []))+ else:+ classes = []++ # If no classes, try to extract from semantic network+ if not classes and isinstance(ontology, dict):+ # Check if it's a semantic model or semantic network+ semantic_network = ontology.get("semantic_network", ontology.get("network"))+ if semantic_network:+ classes = self._extract_classes_from_semantic_network(semantic_network)++ if not classes:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="No classes found in ontology")+ raise ProcessingError("No classes found in ontology. Please provide classes or a semantic network.")++ # If output is dot and graphviz is available, use it+ if output == "dot" and graphviz is not None and file_path:+ self.progress_tracker.update_tracking(tracking_id, message="Generating Graphviz visualization...")+ result = self._visualize_hierarchy_graphviz(classes, file_path, **options)+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Hierarchy visualized: {len(classes)} classes")+ return result++ # Build hierarchy tree+ self.progress_tracker.update_tracking(tracking_id, message="Building hierarchy tree...")+ hierarchy = self._build_hierarchy_tree(classes)++ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ result = self._visualize_hierarchy_plotly(hierarchy, classes, output, file_path, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Hierarchy visualized: {len(classes)} classes")+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_properties(self,diff --git a/semantica/visualization/quality_visualizer.py b/semantica/visualization/quality_visualizer.pyindex 87c59549..260aaaa5 100644--- a/semantica/visualization/quality_visualizer.py+++ b/semantica/visualization/quality_visualizer.py@@ -39,6 +39,7 @@ from plotly.subplots import make_subplotsfrom ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.color_schemes import ColorSchemefrom .utils.export_formats import export_plotly_figure@@ -58,6 +59,7 @@ class QualityVisualizer:"""Initialize quality visualizer."""self.logger = get_logger("quality_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()color_scheme_name = config.get("color_scheme", "default")try:self.color_scheme = ColorScheme[color_scheme_name.upper()]@@ -83,95 +85,111 @@ class QualityVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing quality dashboard")-- # Extract metrics- if hasattr(quality_report, "overall_score"):- overall_score = quality_report.overall_score- consistency_score = quality_report.consistency_score- completeness_score = quality_report.completeness_score- elif isinstance(quality_report, dict):- overall_score = quality_report.get("overall_score", 0.0)- consistency_score = quality_report.get("consistency_score", 0.0)- completeness_score = quality_report.get("completeness_score", 0.0)- else:- overall_score = 0.0- consistency_score = 0.0- completeness_score = 0.0-- # Create dashboard- fig = make_subplots(- rows=2, cols=2,- subplot_titles=("Overall Quality Score", "Consistency Score", "Completeness Score", "Quality Breakdown"),- specs=[[{"type": "indicator"}, {"type": "indicator"}],- [{"type": "indicator"}, {"type": "bar"}]]- )-- # Overall score- fig.add_trace(go.Indicator(- mode="gauge+number",- value=overall_score * 100,- domain={'x': [0, 1], 'y': [0, 1]},- title={'text': "Overall Quality"},- gauge={'axis': {'range': [None, 100]},- 'bar': {'color': "darkblue"},- 'steps': [{'range': [0, 50], 'color': "lightgray"},- {'range': [50, 80], 'color': "gray"}],- 'threshold': {'line': {'color': "red", 'width': 4},- 'thickness': 0.75, 'value': 90}}- ), row=1, col=1)-- # Consistency score- fig.add_trace(go.Indicator(- mode="gauge+number",- value=consistency_score * 100,- domain={'x': [0, 1], 'y': [0, 1]},- title={'text': "Consistency"},- gauge={'axis': {'range': [None, 100]},- 'bar': {'color': "darkgreen"},- 'steps': [{'range': [0, 50], 'color': "lightgray"},- {'range': [50, 80], 'color': "gray"}],- 'threshold': {'line': {'color': "red", 'width': 4},- 'thickness': 0.75, 'value': 90}}- ), row=1, col=2)-- # Completeness score- fig.add_trace(go.Indicator(- mode="gauge+number",- value=completeness_score * 100,- domain={'x': [0, 1], 'y': [0, 1]},- title={'text': "Completeness"},- gauge={'axis': {'range': [None, 100]},- 'bar': {'color': "darkorange"},- 'steps': [{'range': [0, 50], 'color': "lightgray"},- {'range': [50, 80], 'color': "gray"}],- 'threshold': {'line': {'color': "red", 'width': 4},- 'thickness': 0.75, 'value': 90}}- ), row=2, col=1)-- # Quality breakdown- metrics = {- "Overall": overall_score * 100,- "Consistency": consistency_score * 100,- "Completeness": completeness_score * 100- }-- fig.add_trace(go.Bar(- x=list(metrics.keys()),- y=list(metrics.values()),- marker_color='lightblue'- ), row=2, col=2)-- fig.update_layout(- title="Knowledge Graph Quality Dashboard",- height=800+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="QualityVisualizer",+ message="Visualizing quality dashboard")- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None+ try:+ self.logger.info("Visualizing quality dashboard")++ # Extract metrics+ self.progress_tracker.update_tracking(tracking_id, message="Extracting quality metrics...")+ if hasattr(quality_report, "overall_score"):+ overall_score = quality_report.overall_score+ consistency_score = quality_report.consistency_score+ completeness_score = quality_report.completeness_score+ elif isinstance(quality_report, dict):+ overall_score = quality_report.get("overall_score", 0.0)+ consistency_score = quality_report.get("consistency_score", 0.0)+ completeness_score = quality_report.get("completeness_score", 0.0)+ else:+ overall_score = 0.0+ consistency_score = 0.0+ completeness_score = 0.0++ # Create dashboard+ self.progress_tracker.update_tracking(tracking_id, message="Creating dashboard visualization...")+ fig = make_subplots(+ rows=2, cols=2,+ subplot_titles=("Overall Quality Score", "Consistency Score", "Completeness Score", "Quality Breakdown"),+ specs=[[{"type": "indicator"}, {"type": "indicator"}],+ [{"type": "indicator"}, {"type": "bar"}]]+ )++ # Overall score+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=overall_score * 100,+ domain={'x': [0, 1], 'y': [0, 1]},+ title={'text': "Overall Quality"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkblue"},+ 'steps': [{'range': [0, 50], 'color': "lightgray"},+ {'range': [50, 80], 'color': "gray"}],+ 'threshold': {'line': {'color': "red", 'width': 4},+ 'thickness': 0.75, 'value': 90}}+ ), row=1, col=1)++ # Consistency score+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=consistency_score * 100,+ domain={'x': [0, 1], 'y': [0, 1]},+ title={'text': "Consistency"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkgreen"},+ 'steps': [{'range': [0, 50], 'color': "lightgray"},+ {'range': [50, 80], 'color': "gray"}],+ 'threshold': {'line': {'color': "red", 'width': 4},+ 'thickness': 0.75, 'value': 90}}+ ), row=1, col=2)++ # Completeness score+ fig.add_trace(go.Indicator(+ mode="gauge+number",+ value=completeness_score * 100,+ domain={'x': [0, 1], 'y': [0, 1]},+ title={'text': "Completeness"},+ gauge={'axis': {'range': [None, 100]},+ 'bar': {'color': "darkorange"},+ 'steps': [{'range': [0, 50], 'color': "lightgray"},+ {'range': [50, 80], 'color': "gray"}],+ 'threshold': {'line': {'color': "red", 'width': 4},+ 'thickness': 0.75, 'value': 90}}+ ), row=2, col=1)++ # Quality breakdown+ metrics = {+ "Overall": overall_score * 100,+ "Consistency": consistency_score * 100,+ "Completeness": completeness_score * 100+ }++ fig.add_trace(go.Bar(+ x=list(metrics.keys()),+ y=list(metrics.values()),+ marker_color='lightblue'+ ), row=2, col=2)++ fig.update_layout(+ title="Knowledge Graph Quality Dashboard",+ height=800+ )++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message="Quality dashboard visualization generated")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Quality dashboard saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_score_distribution(self,diff --git a/semantica/visualization/semantic_network_visualizer.py b/semantica/visualization/semantic_network_visualizer.pyindex 61b58ef0..d7134f14 100644--- a/semantica/visualization/semantic_network_visualizer.py+++ b/semantica/visualization/semantic_network_visualizer.py@@ -38,6 +38,7 @@ import plotly.express as pxfrom ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.layout_algorithms import ForceDirectedLayoutfrom .utils.color_schemes import ColorPalette, ColorSchemefrom .utils.export_formats import export_plotly_figure@@ -54,6 +55,7 @@ class SemanticNetworkVisualizer:"""Initialize semantic network visualizer."""self.logger = get_logger("semantic_network_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()color_scheme_name = config.get("color_scheme", "default")try:self.color_scheme = ColorScheme[color_scheme_name.upper()]@@ -85,51 +87,23 @@ class SemanticNetworkVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing semantic network")-- # Extract nodes and edges from semantic network- nodes = []- edges = []+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="SemanticNetworkVisualizer",+ message="Visualizing semantic network"+ )- # Handle SemanticNetwork dataclass- if hasattr(semantic_network, "nodes") and hasattr(semantic_network, "edges"):- for node in semantic_network.nodes:- nodes.append({- "id": getattr(node, "id", ""),- "label": getattr(node, "label", ""),- "type": getattr(node, "type", "entity"),- "metadata": getattr(node, "metadata", {}) or {},- "properties": getattr(node, "properties", {}) or {}- })+ try:+ self.logger.info("Visualizing semantic network")- for edge in semantic_network.edges:- edges.append({- "source": getattr(edge, "source", ""),- "target": getattr(edge, "target", ""),- "label": getattr(edge, "label", ""),- "type": getattr(edge, "label", ""),- "metadata": getattr(edge, "metadata", {}) or {},- "properties": getattr(edge, "properties", {}) or {}- })-- # Handle dictionary format- elif isinstance(semantic_network, dict):- # Check if it's a semantic model from ontology generator- if "semantic_network" in semantic_network:- semantic_network = semantic_network["semantic_network"]+ # Extract nodes and edges from semantic network+ self.progress_tracker.update_tracking(tracking_id, message="Extracting nodes and edges...")+ nodes = []+ edges = []- # Extract nodes- network_nodes = semantic_network.get("nodes", [])- for node in network_nodes:- if isinstance(node, dict):- nodes.append({- "id": node.get("id", node.get("uri", "")),- "label": node.get("label", node.get("name", "")),- "type": node.get("type", node.get("class", "entity")),- "metadata": node.get("metadata", {}),- "properties": node.get("properties", {})- })- elif hasattr(node, "id"):+ # Handle SemanticNetwork dataclass+ if hasattr(semantic_network, "nodes") and hasattr(semantic_network, "edges"):+ for node in semantic_network.nodes:nodes.append({"id": getattr(node, "id", ""),"label": getattr(node, "label", ""),@@ -137,20 +111,8 @@ class SemanticNetworkVisualizer:"metadata": getattr(node, "metadata", {}) or {},"properties": getattr(node, "properties", {}) or {}})-- # Extract edges- network_edges = semantic_network.get("edges", semantic_network.get("relationships", []))- for edge in network_edges:- if isinstance(edge, dict):- edges.append({- "source": edge.get("source", edge.get("subject", "")),- "target": edge.get("target", edge.get("object", "")),- "label": edge.get("label", edge.get("predicate", edge.get("type", ""))),- "type": edge.get("type", edge.get("predicate", "")),- "metadata": edge.get("metadata", {}),- "properties": edge.get("properties", {})- })- elif hasattr(edge, "source"):++ for edge in semantic_network.edges:edges.append({"source": getattr(edge, "source", ""),"target": getattr(edge, "target", ""),@@ -159,39 +121,97 @@ class SemanticNetworkVisualizer:"metadata": getattr(edge, "metadata", {}) or {},"properties": getattr(edge, "properties", {}) or {}})-- # Handle entities/relationships format (for semantic models)- elif isinstance(semantic_network, (list, tuple)):- # Assume it's a list of entities/relationships- for item in semantic_network:- if isinstance(item, dict):- if "source" in item or "subject" in item:- edges.append({- "source": item.get("source", item.get("subject", "")),- "target": item.get("target", item.get("object", "")),- "label": item.get("label", item.get("predicate", item.get("type", ""))),- "type": item.get("type", ""),- "metadata": item.get("metadata", {})++ # Handle dictionary format+ elif isinstance(semantic_network, dict):+ # Check if it's a semantic model from ontology generator+ if "semantic_network" in semantic_network:+ semantic_network = semantic_network["semantic_network"]++ # Extract nodes+ network_nodes = semantic_network.get("nodes", [])+ for node in network_nodes:+ if isinstance(node, dict):+ nodes.append({+ "id": node.get("id", node.get("uri", "")),+ "label": node.get("label", node.get("name", "")),+ "type": node.get("type", node.get("class", "entity")),+ "metadata": node.get("metadata", {}),+ "properties": node.get("properties", {})})- else:+ elif hasattr(node, "id"):nodes.append({- "id": item.get("id", item.get("uri", "")),- "label": item.get("label", item.get("name", "")),- "type": item.get("type", "entity"),- "metadata": item.get("metadata", {})+ "id": getattr(node, "id", ""),+ "label": getattr(node, "label", ""),+ "type": getattr(node, "type", "entity"),+ "metadata": getattr(node, "metadata", {}) or {},+ "properties": getattr(node, "properties", {}) or {}})-- if not nodes and not edges:- raise ProcessingError(- "Could not extract nodes and edges from semantic network. "- "Please provide a SemanticNetwork object, dict with 'nodes'/'edges', or semantic model."- )-- # Use KG visualizer for network visualization- from .kg_visualizer import KGVisualizer- graph = {"entities": nodes, "relationships": edges}- kg_viz = KGVisualizer(**self.config)- return kg_viz.visualize_network(graph, output, file_path, **options)++ # Extract edges+ network_edges = semantic_network.get("edges", semantic_network.get("relationships", []))+ for edge in network_edges:+ if isinstance(edge, dict):+ edges.append({+ "source": edge.get("source", edge.get("subject", "")),+ "target": edge.get("target", edge.get("object", "")),+ "label": edge.get("label", edge.get("predicate", edge.get("type", ""))),+ "type": edge.get("type", edge.get("predicate", "")),+ "metadata": edge.get("metadata", {}),+ "properties": edge.get("properties", {})+ })+ elif hasattr(edge, "source"):+ edges.append({+ "source": getattr(edge, "source", ""),+ "target": getattr(edge, "target", ""),+ "label": getattr(edge, "label", ""),+ "type": getattr(edge, "label", ""),+ "metadata": getattr(edge, "metadata", {}) or {},+ "properties": getattr(edge, "properties", {}) or {}+ })++ # Handle entities/relationships format (for semantic models)+ elif isinstance(semantic_network, (list, tuple)):+ # Assume it's a list of entities/relationships+ for item in semantic_network:+ if isinstance(item, dict):+ if "source" in item or "subject" in item:+ edges.append({+ "source": item.get("source", item.get("subject", "")),+ "target": item.get("target", item.get("object", "")),+ "label": item.get("label", item.get("predicate", item.get("type", ""))),+ "type": item.get("type", ""),+ "metadata": item.get("metadata", {})+ })+ else:+ nodes.append({+ "id": item.get("id", item.get("uri", "")),+ "label": item.get("label", item.get("name", "")),+ "type": item.get("type", "entity"),+ "metadata": item.get("metadata", {})+ })++ if not nodes and not edges:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="Could not extract nodes and edges from semantic network")+ raise ProcessingError(+ "Could not extract nodes and edges from semantic network. "+ "Please provide a SemanticNetwork object, dict with 'nodes'/'edges', or semantic model."+ )++ # Use KG visualizer for network visualization+ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ from .kg_visualizer import KGVisualizer+ graph = {"entities": nodes, "relationships": edges}+ kg_viz = KGVisualizer(**self.config)+ result = kg_viz.visualize_network(graph, output, file_path, **options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Visualization generated: {len(nodes)} nodes, {len(edges)} edges")+ return result+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_node_types(self,diff --git a/semantica/visualization/temporal_visualizer.py b/semantica/visualization/temporal_visualizer.pyindex 3ad81d3b..fa310491 100644--- a/semantica/visualization/temporal_visualizer.py+++ b/semantica/visualization/temporal_visualizer.py@@ -39,6 +39,7 @@ from plotly.subplots import make_subplotsfrom ..utils.logging import get_loggerfrom ..utils.exceptions import ProcessingError+from ..utils.progress_tracker import get_progress_trackerfrom .utils.color_schemes import ColorPalette, ColorSchemefrom .utils.export_formats import export_plotly_figure@@ -58,6 +59,7 @@ class TemporalVisualizer:"""Initialize temporal visualizer."""self.logger = get_logger("temporal_visualizer")self.config = config+ self.progress_tracker = get_progress_tracker()color_scheme_name = config.get("color_scheme", "default")try:self.color_scheme = ColorScheme[color_scheme_name.upper()]@@ -83,67 +85,86 @@ class TemporalVisualizer:Returns:Visualization figure or None"""- self.logger.info("Visualizing temporal timeline")-- # Extract timeline data- events = temporal_data.get("events", [])- timestamps = temporal_data.get("timestamps", [])-- if not events:- raise ProcessingError("No temporal events found")-- # Build timeline- event_types = []- event_times = []- event_labels = []+ tracking_id = self.progress_tracker.start_tracking(+ module="visualization",+ submodule="TemporalVisualizer",+ message="Visualizing temporal timeline"+ )- for event in events:- event_time = event.get("timestamp") or event.get("time", "")- event_type = event.get("type") or event.get("event_type", "change")- event_label = event.get("label") or event.get("entity", "")+ try:+ self.logger.info("Visualizing temporal timeline")- event_times.append(event_time)- event_types.append(event_type)- event_labels.append(event_label)-- # Create Gantt chart style timeline- fig = go.Figure()-- # Group by type- type_colors = {}- unique_types = list(set(event_types))- colors = ColorPalette.get_colors(self.color_scheme, len(unique_types))- for i, t in enumerate(unique_types):- type_colors[t] = colors[i]-- for event_type in unique_types:- mask = [t == event_type for t in event_types]- type_times = [event_times[i] for i in range(len(event_times)) if mask[i]]- type_labels = [event_labels[i] for i in range(len(event_labels)) if mask[i]]+ # Extract timeline data+ self.progress_tracker.update_tracking(tracking_id, message="Extracting timeline data...")+ events = temporal_data.get("events", [])+ timestamps = temporal_data.get("timestamps", [])- fig.add_trace(go.Scatter(- x=type_times,- y=[event_type] * len(type_times),- mode='markers',- name=event_type,- marker=dict(size=10, color=type_colors[event_type]),- text=type_labels,- hovertemplate='%{text}<br>Time: %{x}<extra></extra>'- ))-- fig.update_layout(- title="Temporal Timeline",- xaxis_title="Time",- yaxis_title="Event Type",- width=1200,- height=600- )-- if output == "interactive":- return fig- elif file_path:- export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")- return None+ if not events:+ self.progress_tracker.stop_tracking(tracking_id, status="failed",+ message="No temporal events found")+ raise ProcessingError("No temporal events found")++ # Build timeline+ self.progress_tracker.update_tracking(tracking_id, message="Building timeline...")+ event_types = []+ event_times = []+ event_labels = []++ for event in events:+ event_time = event.get("timestamp") or event.get("time", "")+ event_type = event.get("type") or event.get("event_type", "change")+ event_label = event.get("label") or event.get("entity", "")++ event_times.append(event_time)+ event_types.append(event_type)+ event_labels.append(event_label)++ # Create Gantt chart style timeline+ self.progress_tracker.update_tracking(tracking_id, message="Generating visualization...")+ fig = go.Figure()++ # Group by type+ type_colors = {}+ unique_types = list(set(event_types))+ colors = ColorPalette.get_colors(self.color_scheme, len(unique_types))+ for i, t in enumerate(unique_types):+ type_colors[t] = colors[i]++ for event_type in unique_types:+ mask = [t == event_type for t in event_types]+ type_times = [event_times[i] for i in range(len(event_times)) if mask[i]]+ type_labels = [event_labels[i] for i in range(len(event_labels)) if mask[i]]++ fig.add_trace(go.Scatter(+ x=type_times,+ y=[event_type] * len(type_times),+ mode='markers',+ name=event_type,+ marker=dict(size=10, color=type_colors[event_type]),+ text=type_labels,+ hovertemplate='%{text}<br>Time: %{x}<extra></extra>'+ ))++ fig.update_layout(+ title="Temporal Timeline",+ xaxis_title="Time",+ yaxis_title="Event Type",+ width=1200,+ height=600+ )++ if output == "interactive":+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Timeline visualization generated: {len(events)} events")+ return fig+ elif file_path:+ export_plotly_figure(fig, file_path, format=output if output != "interactive" else "html")+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Timeline saved to {file_path}")+ return None+ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef visualize_temporal_patterns(self,