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 comprehensive progress tracking to all ingestion and parsing modules
KaifAhmad1af65e4e90b75
diff --git a/semantica/core/orchestrator.py b/semantica/core/orchestrator.pyindex 3d4a704c..a97554a1 100644--- a/semantica/core/orchestrator.py+++ b/semantica/core/orchestrator.py@@ -32,6 +32,7 @@ from .lifecycle import LifecycleManager, SystemStatefrom .plugin_registry import PluginRegistryfrom ..utils.exceptions import ConfigurationError, ProcessingErrorfrom ..utils.logging import get_logger, log_execution_time+from ..utils.progress_tracker import get_progress_trackerclass Semantica:@@ -87,6 +88,9 @@ class Semantica:self._modules: Dict[str, Any] = {}self._initialized: bool = False+ # Initialize progress tracker (automatic, zero configuration)+ self.progress_tracker = get_progress_tracker()+self.logger.info("Semantica framework initialized")@log_execution_time@@ -169,6 +173,13 @@ class Semantica:# Auto-initialize if not already initializedself._ensure_initialized()+ # Start overall progress tracking+ overall_tracking_id = self.progress_tracker.start_tracking(+ module="core",+ submodule="Semantica",+ message=f"Building knowledge base from {len(sources)} sources"+ )+try:self.logger.info(f"Building knowledge base from {len(sources)} sources")@@ -183,8 +194,23 @@ class Semantica:results = []for source in validated_sources:try:- result = self.run_pipeline(pipeline, source)- results.append(result)+ # Track file processing+ file_str = str(source)+ file_tracking_id = self.progress_tracker.start_tracking(+ file=file_str,+ module="core",+ submodule="build_knowledge_base",+ message=f"Processing {Path(file_str).name if file_str else 'source'}"+ )+ try:+ result = self.run_pipeline(pipeline, source)+ results.append(result)+ self.progress_tracker.stop_tracking(file_tracking_id, status="completed")+ except Exception as e:+ self.progress_tracker.stop_tracking(file_tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to process source {source}: {e}")+ if kwargs.get("fail_fast", False):+ raise ProcessingError(f"Failed to process source {source}: {e}")except Exception as e:self.logger.error(f"Failed to process source {source}: {e}")if kwargs.get("fail_fast", False):@@ -207,6 +233,13 @@ class Semantica:"success_rate": len([r for r in results if r.get("success")]) / len(results) if results else 0.0,}+ # Stop overall tracking+ self.progress_tracker.stop_tracking(overall_tracking_id, status="completed",+ message=f"Processed {len(results)} sources")++ # Show summary+ self.progress_tracker.show_summary()+return {"knowledge_graph": knowledge_graph,"embeddings": embeddings,@@ -219,6 +252,7 @@ class Semantica:}except Exception as e:+ self.progress_tracker.stop_tracking(overall_tracking_id, status="failed", message=str(e))self.logger.error(f"Failed to build knowledge base: {e}")raise ProcessingError(f"Failed to build knowledge base: {e}")@@ -240,9 +274,18 @@ class Semantica:Raises:ProcessingError: If pipeline execution fails"""+ pipeline_tracking_id = Nonetry:self.logger.info("Executing processing pipeline")+ # Track pipeline execution+ pipeline_tracking_id = self.progress_tracker.start_tracking(+ file=str(data) if isinstance(data, (str, Path)) else None,+ module="pipeline",+ submodule="ExecutionEngine",+ message="Executing pipeline"+ )+# Validate pipelineif isinstance(pipeline, dict):pipeline = self._create_pipeline_from_dict(pipeline)@@ -261,6 +304,9 @@ class Semantica:# Collect metricsmetrics = self._collect_metrics(pipeline)+ if pipeline_tracking_id:+ self.progress_tracker.stop_tracking(pipeline_tracking_id, status="completed")+return {"success": True,"output": result,@@ -276,6 +322,8 @@ class Semantica:self._release_resources(resources)except Exception as e:+ if pipeline_tracking_id:+ self.progress_tracker.stop_tracking(pipeline_tracking_id, status="failed", message=str(e))self.logger.error(f"Pipeline execution failed: {e}")raise ProcessingError(f"Pipeline execution failed: {e}")@@ -538,11 +586,22 @@ class Semantica:self.logger.warning("No entities or relationships found in results")return {"entities": [], "relationships": [], "metadata": {}}- # Build knowledge graph- graph_builder = GraphBuilder(merge_entities=True, resolve_conflicts=True)- knowledge_graph = graph_builder.build(graph_sources)+ # Track knowledge graph building+ kg_tracking_id = self.progress_tracker.start_tracking(+ module="kg",+ submodule="GraphBuilder",+ message="Building knowledge graph"+ )- return knowledge_graph+ try:+ # Build knowledge graph+ graph_builder = GraphBuilder(merge_entities=True, resolve_conflicts=True)+ knowledge_graph = graph_builder.build(graph_sources)+ self.progress_tracker.stop_tracking(kg_tracking_id, status="completed")+ return knowledge_graph+ except Exception as e:+ self.progress_tracker.stop_tracking(kg_tracking_id, status="failed", message=str(e))+ raiseexcept ImportError:self.logger.warning("KG module not available, returning placeholder")@@ -581,18 +640,31 @@ class Semantica:self.logger.warning("No text content found in results for embedding")return {"embeddings": [], "metadata": {}}- # Generate embeddings- embedding_generator = EmbeddingGenerator()- embeddings_result = embedding_generator.process_batch(texts_to_embed)+ # Track embedding generation+ embed_tracking_id = self.progress_tracker.start_tracking(+ module="embeddings",+ submodule="EmbeddingGenerator",+ message=f"Generating embeddings for {len(texts_to_embed)} texts"+ )- return {- "embeddings": embeddings_result["embeddings"],- "metadata": {- "total_texts": len(texts_to_embed),- "successful": embeddings_result["success_count"],- "failed": embeddings_result["failure_count"]+ try:+ # Generate embeddings+ embedding_generator = EmbeddingGenerator()+ embeddings_result = embedding_generator.process_batch(texts_to_embed)+ self.progress_tracker.stop_tracking(embed_tracking_id, status="completed",+ message=f"Generated {embeddings_result.get('success_count', 0)} embeddings")++ return {+ "embeddings": embeddings_result["embeddings"],+ "metadata": {+ "total_texts": len(texts_to_embed),+ "successful": embeddings_result["success_count"],+ "failed": embeddings_result["failure_count"]+ }}- }+ except Exception as e:+ self.progress_tracker.stop_tracking(embed_tracking_id, status="failed", message=str(e))+ raiseexcept ImportError:self.logger.warning("Embeddings module not available, returning placeholder")diff --git a/semantica/embeddings/embedding_generator.py b/semantica/embeddings/embedding_generator.pyindex 7d1def6b..b3e4959b 100644--- a/semantica/embeddings/embedding_generator.py+++ b/semantica/embeddings/embedding_generator.py@@ -99,6 +99,10 @@ class EmbeddingGenerator:# List of supported embedding modelsself.supported_models = ["sentence-transformers", "openai", "bge", "clip"]+ # Initialize progress tracker+ from ..utils.progress_tracker import get_progress_tracker+ self.progress_tracker = get_progress_tracker()+self.logger.info("Embedding generator initialized")def generate_embeddings(@@ -280,28 +284,44 @@ class EmbeddingGenerator:Returns:dict: Batch processing results"""- results = {- "embeddings": [],- "successful": [],- "failed": []- }-- for item in data_items:- try:- embedding = self.generate_embeddings(item, **options)- results["embeddings"].append(embedding)- results["successful"].append(str(item))- except Exception as e:- results["failed"].append({- "item": str(item),- "error": str(e)- })+ # Track batch processing+ tracking_id = self.progress_tracker.start_tracking(+ module="embeddings",+ submodule="EmbeddingGenerator",+ message=f"Batch of {len(data_items)} items"+ )- results["total"] = len(data_items)- results["success_count"] = len(results["successful"])- results["failure_count"] = len(results["failed"])-- return results+ try:+ results = {+ "embeddings": [],+ "successful": [],+ "failed": []+ }++ for idx, item in enumerate(data_items, 1):+ try:+ self.progress_tracker.update_tracking(tracking_id,+ message=f"Processing item {idx}/{len(data_items)}")+ embedding = self.generate_embeddings(item, **options)+ results["embeddings"].append(embedding)+ results["successful"].append(str(item))+ except Exception as e:+ results["failed"].append({+ "item": str(item),+ "error": str(e)+ })++ results["total"] = len(data_items)+ results["success_count"] = len(results["successful"])+ results["failure_count"] = len(results["failed"])++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Processed {results['success_count']}/{len(data_items)} items successfully")+ return results++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raise# Re-export classes from other modules for conveniencediff --git a/semantica/ingest/db_ingestor.py b/semantica/ingest/db_ingestor.pyindex 9a12097e..ec82e3a0 100644--- a/semantica/ingest/db_ingestor.py+++ b/semantica/ingest/db_ingestor.py@@ -40,6 +40,7 @@ from sqlalchemy.engine import Enginefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -528,6 +529,9 @@ class DBIngestor:# Supported databasesself.supported_databases = list(DatabaseConnector.SUPPORTED_DATABASES.keys())+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.logger.debug(f"DB ingestor initialized with support for: {', '.join(self.supported_databases)}")@@ -564,65 +568,86 @@ class DBIngestor:- total_tables: Total number of tables exported- connection_string: Connection string used"""- # Connect to database- connector = DatabaseConnector("", **self.config)- engine = connector.connect(connection_string)+ # Track database ingestion+ tracking_id = self.progress_tracker.start_tracking(+ file=connection_string.split('@')[-1] if '@' in connection_string else connection_string,+ module="ingest",+ submodule="DBIngestor",+ message=f"Database: {connection_string.split('@')[-1] if '@' in connection_string else 'database'}"+ )try:- # Analyze schema first- schema = self.analyze_schema(connection_string)-- # Get all table names- inspector = inspect(engine)- all_tables = inspector.get_table_names()-- self.logger.debug(f"Found {len(all_tables)} table(s) in database")-- # Apply table filters- if include_tables:- tables = [t for t in all_tables if t in include_tables]- self.logger.debug(f"Filtered to {len(tables)} table(s) via include_tables")- else:- exclude_tables = exclude_tables or []- tables = [t for t in all_tables if t not in exclude_tables]- if exclude_tables:- self.logger.debug(f"Filtered to {len(tables)} table(s) via exclude_tables")-- # Export data from each table- table_data = {}-- for table_name in tables:- try:- # Export table with optional row limit- table_info = self.exporter.export_table_data(- engine,- table_name,- limit=max_rows_per_table- )- table_data[table_name] = {- "columns": table_info.columns,- "row_count": table_info.row_count,- "rows": table_info.rows- }- self.logger.debug(- f"Exported table {table_name}: {table_info.row_count} row(s)"- )- except Exception as e:- self.logger.error(f"Failed to export table {table_name}: {e}")- if self.config.get('fail_fast', False):- raise ProcessingError(f"Failed to export table {table_name}: {e}") from e-- self.logger.info(- f"Database ingestion completed: {len(table_data)} table(s) exported"- )-- return {- "schema": schema,- "tables": table_data,- "total_tables": len(tables),- "connection_string": connection_string- }+ # Connect to database+ connector = DatabaseConnector("", **self.config)+ engine = connector.connect(connection_string)+ try:+ # Analyze schema first+ self.progress_tracker.update_tracking(tracking_id, message="Analyzing schema...")+ schema = self.analyze_schema(connection_string)++ # Get all table names+ inspector = inspect(engine)+ all_tables = inspector.get_table_names()++ self.logger.debug(f"Found {len(all_tables)} table(s) in database")++ # Apply table filters+ if include_tables:+ tables = [t for t in all_tables if t in include_tables]+ self.logger.debug(f"Filtered to {len(tables)} table(s) via include_tables")+ else:+ exclude_tables = exclude_tables or []+ tables = [t for t in all_tables if t not in exclude_tables]+ if exclude_tables:+ self.logger.debug(f"Filtered to {len(tables)} table(s) via exclude_tables")++ self.progress_tracker.update_tracking(tracking_id, message=f"Exporting {len(tables)} tables...")++ # Export data from each table+ table_data = {}++ for table_name in tables:+ try:+ # Export table with optional row limit+ table_info = self.exporter.export_table_data(+ engine,+ table_name,+ limit=max_rows_per_table+ )+ table_data[table_name] = {+ "columns": table_info.columns,+ "row_count": table_info.row_count,+ "rows": table_info.rows+ }+ self.logger.debug(+ f"Exported table {table_name}: {table_info.row_count} row(s)"+ )+ except Exception as e:+ self.logger.error(f"Failed to export table {table_name}: {e}")+ if self.config.get('fail_fast', False):+ raise ProcessingError(f"Failed to export table {table_name}: {e}") from e++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Exported {len(table_data)} tables")+ self.logger.info(+ f"Database ingestion completed: {len(table_data)} table(s) exported"+ )++ return {+ "schema": schema,+ "tables": table_data,+ "total_tables": len(table_data),+ "connection_string": connection_string+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raise++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisefinally:connector.disconnect()diff --git a/semantica/ingest/email_ingestor.py b/semantica/ingest/email_ingestor.pyindex 8f3c9bea..800aa4f9 100644--- a/semantica/ingest/email_ingestor.py+++ b/semantica/ingest/email_ingestor.py@@ -44,6 +44,7 @@ from bs4 import BeautifulSoupfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -445,6 +446,9 @@ class EmailIngestor:self.imap_client: Optional[imaplib.IMAP4_SSL] = Noneself.pop3_client: Optional[poplib.POP3_SSL] = None+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.logger.debug("Email ingestor initialized")def connect_imap(diff --git a/semantica/ingest/feed_ingestor.py b/semantica/ingest/feed_ingestor.pyindex 81b0ca4e..aea90416 100644--- a/semantica/ingest/feed_ingestor.py+++ b/semantica/ingest/feed_ingestor.py@@ -41,6 +41,7 @@ from bs4 import BeautifulSoupfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -573,6 +574,9 @@ class FeedIngestor:# Update intervalsself.update_intervals = self.config.get("update_intervals", {})+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.logger.debug("Feed ingestor initialized")def ingest_feed(@@ -601,34 +605,51 @@ class FeedIngestor:ValidationError: If feed URL is invalidProcessingError: If feed fetching or parsing fails"""- # Validate feed URL- try:- parsed = urlparse(feed_url)- if not parsed.scheme or not parsed.netloc:- raise ValidationError(f"Invalid feed URL: {feed_url}")- except Exception as e:- raise ValidationError(f"Invalid feed URL: {feed_url}") from e+ # Track feed ingestion+ tracking_id = self.progress_tracker.start_tracking(+ file=feed_url,+ module="ingest",+ submodule="FeedIngestor",+ message=f"Feed: {feed_url}"+ )- # Fetch feed contenttry:- request_timeout = timeout or options.get("timeout", self.config.get("timeout", 30))- response = requests.get(feed_url, timeout=request_timeout)- response.raise_for_status()- self.logger.debug(f"Fetched feed from {feed_url}: {len(response.text)} bytes")- except requests.RequestException as e:- self.logger.error(f"Failed to fetch feed {feed_url}: {e}")- raise ProcessingError(f"Failed to fetch feed: {e}") from e-- # Parse feed format- feed_data = self.parser.parse_feed(response.text, feed_url)-- # Validate feed- if validate or options.get("validate", True):- if not self.parser.validate_feed(feed_data):- self.logger.warning(f"Feed {feed_url} validation failed")-- self.logger.info(f"Ingested feed {feed_url}: {len(feed_data.items)} item(s)")- return feed_data+ # Validate feed URL+ try:+ parsed = urlparse(feed_url)+ if not parsed.scheme or not parsed.netloc:+ raise ValidationError(f"Invalid feed URL: {feed_url}")+ except Exception as e:+ raise ValidationError(f"Invalid feed URL: {feed_url}") from e++ # Fetch feed content+ try:+ request_timeout = timeout or options.get("timeout", self.config.get("timeout", 30))+ response = requests.get(feed_url, timeout=request_timeout)+ response.raise_for_status()+ self.logger.debug(f"Fetched feed from {feed_url}: {len(response.text)} bytes")+ except requests.RequestException as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to fetch feed {feed_url}: {e}")+ raise ProcessingError(f"Failed to fetch feed: {e}") from e++ # Parse feed format+ feed_data = self.parser.parse_feed(response.text, feed_url)++ # Validate feed+ if validate or options.get("validate", True):+ if not self.parser.validate_feed(feed_data):+ self.logger.warning(f"Feed {feed_url} validation failed")++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Ingested {len(feed_data.items)} items")+ self.logger.info(f"Ingested feed {feed_url}: {len(feed_data.items)} item(s)")++ return feed_data++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef discover_feeds(self, website_url: str) -> List[str]:"""diff --git a/semantica/ingest/file_ingestor.py b/semantica/ingest/file_ingestor.pyindex c0f6d4b5..c48c811b 100644--- a/semantica/ingest/file_ingestor.py+++ b/semantica/ingest/file_ingestor.py@@ -31,6 +31,7 @@ from datetime import datetimefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom ..utils.constants import (SUPPORTED_DOCUMENT_FORMATS,SUPPORTED_IMAGE_FORMATS,@@ -391,6 +392,9 @@ class FileIngestor:# Progress tracking callback (can be set by user)self._progress_callback: Optional[callable] = None+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.logger.info("File ingestor initialized")def ingest_directory(@@ -412,37 +416,54 @@ class FileIngestor:"""directory_path = Path(directory_path)- # Validate directory path- if not directory_path.exists():- raise ValidationError(f"Directory not found: {directory_path}")-- if not directory_path.is_dir():- raise ValidationError(f"Path is not a directory: {directory_path}")-- # Scan directory for files- files = self.scan_directory(directory_path, recursive=recursive, **filters)-- # Process each file- file_objects = []- total_files = len(files)-- for idx, file_info in enumerate(files, 1):- try:- file_obj = self.ingest_file(file_info['path'], **file_info)- file_objects.append(file_obj)-- # Track progress- if self._progress_callback:- self._progress_callback(idx, total_files, file_obj)-- self.logger.debug(f"Ingested file {idx}/{total_files}: {file_info['path']}")-- except Exception as e:- self.logger.error(f"Failed to ingest file {file_info['path']}: {e}")- if self.config.get('fail_fast', False):- raise ProcessingError(f"Failed to ingest file: {e}")+ # Track directory ingestion+ tracking_id = self.progress_tracker.start_tracking(+ file=str(directory_path),+ module="ingest",+ submodule="FileIngestor",+ message=f"Directory: {directory_path.name}"+ )- return file_objects+ try:+ # Validate directory path+ if not directory_path.exists():+ raise ValidationError(f"Directory not found: {directory_path}")++ if not directory_path.is_dir():+ raise ValidationError(f"Path is not a directory: {directory_path}")++ # Scan directory for files+ files = self.scan_directory(directory_path, recursive=recursive, **filters)++ # Process each file+ file_objects = []+ total_files = len(files)++ self.progress_tracker.update_tracking(tracking_id, message=f"Processing {total_files} files")++ for idx, file_info in enumerate(files, 1):+ try:+ file_obj = self.ingest_file(file_info['path'], **file_info)+ file_objects.append(file_obj)++ # Track progress+ if self._progress_callback:+ self._progress_callback(idx, total_files, file_obj)++ self.logger.debug(f"Ingested file {idx}/{total_files}: {file_info['path']}")++ except Exception as e:+ self.logger.error(f"Failed to ingest file {file_info['path']}: {e}")+ if self.config.get('fail_fast', False):+ raise ProcessingError(f"Failed to ingest file: {e}")++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Ingested {len(file_objects)} files")+ return file_objects++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef ingest_file(self, file_path: Union[str, Path], **options) -> FileObject:"""@@ -466,67 +487,82 @@ class FileIngestor:"""file_path = Path(file_path)- # Validate file exists- if not file_path.exists():- raise ValidationError(f"File not found: {file_path}")-- # Validate it's actually a file (not a directory)- if not file_path.is_file():- raise ValidationError(f"Path is not a file: {file_path}")-- # Check file size against limits- file_size = file_path.stat().st_size- max_size = FILE_SIZE_LIMITS.get('MAX_DOCUMENT_SIZE', 104857600) # 100MB default- if file_size > max_size:- raise ValidationError(- f"File size {file_size:,} bytes exceeds maximum {max_size:,} bytes "- f"({file_path.name})"- )-- # Detect file type using multiple methods- file_type = self.type_detector.detect_type(file_path)-- # Warn if file type is not in supported formats list- if not self.type_detector.is_supported(file_type):- self.logger.warning(- f"Unsupported file type '{file_type}' for file: {file_path}. "- "Processing may be limited."- )-- # Read file content if requested (default: True)- content = None- read_content = options.get('read_content', True)- if read_content:- try:- with open(file_path, 'rb') as file_handle:- content = file_handle.read()- self.logger.debug(f"Read {len(content):,} bytes from {file_path.name}")- except Exception as e:- self.logger.error(f"Failed to read file content from {file_path}: {e}")- raise ProcessingError(f"Failed to read file: {e}") from e-- # Detect MIME type for additional metadata- mime_type, _ = mimetypes.guess_type(str(file_path))-- # Create and return FileObject with all metadata- file_obj = FileObject(- path=str(file_path.absolute()),- name=file_path.name,- size=file_size,- file_type=file_type,- mime_type=mime_type,- content=content,- metadata={- 'extension': file_path.suffix,- 'parent': str(file_path.parent),- 'is_supported': self.type_detector.is_supported(file_type),- 'read_content': read_content,- **options # Include any additional options as metadata- }+ # Track file ingestion+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="ingest",+ submodule="FileIngestor",+ message=f"File: {file_path.name}")- self.logger.debug(f"Successfully ingested file: {file_path.name} ({file_type})")- return file_obj+ try:+ # Validate file exists+ if not file_path.exists():+ raise ValidationError(f"File not found: {file_path}")++ # Validate it's actually a file (not a directory)+ if not file_path.is_file():+ raise ValidationError(f"Path is not a file: {file_path}")++ # Check file size against limits+ file_size = file_path.stat().st_size+ max_size = FILE_SIZE_LIMITS.get('MAX_DOCUMENT_SIZE', 104857600) # 100MB default+ if file_size > max_size:+ raise ValidationError(+ f"File size {file_size:,} bytes exceeds maximum {max_size:,} bytes "+ f"({file_path.name})"+ )++ # Detect file type using multiple methods+ file_type = self.type_detector.detect_type(file_path)++ # Warn if file type is not in supported formats list+ if not self.type_detector.is_supported(file_type):+ self.logger.warning(+ f"Unsupported file type '{file_type}' for file: {file_path}. "+ "Processing may be limited."+ )++ # Read file content if requested (default: True)+ content = None+ read_content = options.get('read_content', True)+ if read_content:+ try:+ with open(file_path, 'rb') as file_handle:+ content = file_handle.read()+ self.logger.debug(f"Read {len(content):,} bytes from {file_path.name}")+ except Exception as e:+ self.logger.error(f"Failed to read file content from {file_path}: {e}")+ raise ProcessingError(f"Failed to read file: {e}") from e++ # Detect MIME type for additional metadata+ mime_type, _ = mimetypes.guess_type(str(file_path))++ # Create and return FileObject with all metadata+ file_obj = FileObject(+ path=str(file_path.absolute()),+ name=file_path.name,+ size=file_size,+ file_type=file_type,+ mime_type=mime_type,+ content=content,+ metadata={+ 'extension': file_path.suffix,+ 'parent': str(file_path.parent),+ 'is_supported': self.type_detector.is_supported(file_type),+ 'read_content': read_content,+ **options # Include any additional options as metadata+ }+ )++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Ingested {file_path.name} ({file_type})")+ self.logger.debug(f"Successfully ingested file: {file_path.name} ({file_type})")+ return file_obj++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef ingest_cloud(self,diff --git a/semantica/ingest/repo_ingestor.py b/semantica/ingest/repo_ingestor.pyindex cf0243d0..b8bcdd60 100644--- a/semantica/ingest/repo_ingestor.py+++ b/semantica/ingest/repo_ingestor.py@@ -519,45 +519,66 @@ class RepoIngestor:Returns:dict: Processed repository data"""- # Validate repository URL- try:- parsed = git.Repo.clone_from(repo_url, self._get_temp_dir(), **options)- except Exception as e:- raise ProcessingError(f"Failed to clone repository: {e}")-- repo_path = Path(self.temp_dir)- repo = git.Repo(repo_path)+ # Track repository ingestion+ tracking_id = self.progress_tracker.start_tracking(+ file=repo_url,+ module="ingest",+ submodule="RepoIngestor",+ message=f"Repository: {repo_url}"+ )- # Checkout specific branch if requested- if options.get("branch"):+ try:+ # Validate repository URLtry:- repo.git.checkout(options["branch"])+ parsed = git.Repo.clone_from(repo_url, self._get_temp_dir(), **options)except Exception as e:- self.logger.warning(f"Failed to checkout branch {options['branch']}: {e}")-- # Extract repository information- repo_info = self.get_repository_info(repo_url, repo)-- # Process code files- code_files = self.extract_code_files(repo_path, **options.get("file_filters", {}))-- # Analyze commits if requested- commits = []- if options.get("include_history", True):- commits = self.analyze_commits(repo_path, **options.get("commit_filters", {}))-- # Analyze structure- structure = self.analyzer.analyze_structure(repo_path)- metrics = self.analyzer.calculate_metrics(repo_path)-- return {- "repository_info": repo_info,- "code_files": [f.__dict__ for f in code_files],- "commits": [c.__dict__ for c in commits],- "structure": structure,- "metrics": metrics,- "temp_path": str(repo_path)- }+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raise ProcessingError(f"Failed to clone repository: {e}") from e++ repo_path = Path(self.temp_dir)+ repo = git.Repo(repo_path)++ self.progress_tracker.update_tracking(tracking_id, message="Cloning repository...")++ # Checkout specific branch if requested+ if options.get("branch"):+ try:+ repo.git.checkout(options["branch"])+ except Exception as e:+ self.logger.warning(f"Failed to checkout branch {options['branch']}: {e}")++ # Extract repository information+ repo_info = self.get_repository_info(repo_url, repo)++ # Process code files+ self.progress_tracker.update_tracking(tracking_id, message="Extracting code files...")+ code_files = self.extract_code_files(repo_path, **options.get("file_filters", {}))++ # Analyze commits if requested+ commits = []+ if options.get("include_history", True):+ self.progress_tracker.update_tracking(tracking_id, message="Analyzing commits...")+ commits = self.analyze_commits(repo_path, **options.get("commit_filters", {}))++ # Analyze structure+ self.progress_tracker.update_tracking(tracking_id, message="Analyzing structure...")+ structure = self.analyzer.analyze_structure(repo_path)+ metrics = self.analyzer.calculate_metrics(repo_path)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Processed {len(code_files)} files, {len(commits)} commits")+ return {+ "repository_info": repo_info,+ "code_files": [f.__dict__ for f in code_files],+ "commits": [c.__dict__ for c in commits],+ "structure": structure,+ "metrics": metrics,+ "temp_path": str(repo_path)+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef analyze_commits(self, repo_path: Path, **filters) -> List[CommitInfo]:"""diff --git a/semantica/ingest/web_ingestor.py b/semantica/ingest/web_ingestor.pyindex 762666c1..a28ade9b 100644--- a/semantica/ingest/web_ingestor.py+++ b/semantica/ingest/web_ingestor.py@@ -47,6 +47,7 @@ from urllib3.util.retry import Retryfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -544,6 +545,9 @@ class WebIngestor:else:self.robots_checker = None+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+self.logger.debug(f"Web ingestor initialized: user_agent={user_agent}, "f"delay={delay}, respect_robots={respect_robots}"@@ -573,45 +577,61 @@ class WebIngestor:ValidationError: If URL is invalidProcessingError: If URL is blocked by robots.txt or fetch fails"""- # Validate URL format- try:- parsed = urlparse(url)- if not parsed.scheme or not parsed.netloc:- raise ValidationError(- f"Invalid URL format: {url}. "- "URL must include scheme (http/https) and netloc (domain)."- )- except Exception as e:- raise ValidationError(f"Invalid URL: {url}") from e-- # Check robots.txt compliance- if self.robots_checker and not self.robots_checker.can_fetch(url):- self.logger.warning(f"URL {url} blocked by robots.txt")- raise ProcessingError(f"URL blocked by robots.txt: {url}")-- # Apply rate limiting (wait if necessary)- self.rate_limiter.wait_if_needed()-- # Fetch content with retry logic- try:- request_timeout = timeout or self.config.get('timeout', 30)- response = self.session.get(url, timeout=request_timeout)- response.raise_for_status()- except requests.RequestException as e:- self.logger.error(f"Failed to fetch URL {url}: {e}")- raise ProcessingError(f"Failed to fetch URL: {e}") from e-- # Extract content and metadata- html_content = response.text- web_content = self.extract_content(html_content, url=url)- web_content.status_code = response.status_code-- self.logger.debug(- f"Ingested URL: {url}, status={response.status_code}, "- f"text_length={len(web_content.text)}, links={len(web_content.links)}"+ # Track URL ingestion+ tracking_id = self.progress_tracker.start_tracking(+ file=url,+ module="ingest",+ submodule="WebIngestor",+ message=f"URL: {url}")- return web_content+ try:+ # Validate URL format+ try:+ parsed = urlparse(url)+ if not parsed.scheme or not parsed.netloc:+ raise ValidationError(+ f"Invalid URL format: {url}. "+ "URL must include scheme (http/https) and netloc (domain)."+ )+ except Exception as e:+ raise ValidationError(f"Invalid URL: {url}") from e++ # Check robots.txt compliance+ if self.robots_checker and not self.robots_checker.can_fetch(url):+ self.logger.warning(f"URL {url} blocked by robots.txt")+ raise ProcessingError(f"URL blocked by robots.txt: {url}")++ # Apply rate limiting (wait if necessary)+ self.rate_limiter.wait_if_needed()++ # Fetch content with retry logic+ try:+ request_timeout = timeout or self.config.get('timeout', 30)+ response = self.session.get(url, timeout=request_timeout)+ response.raise_for_status()+ except requests.RequestException as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to fetch URL {url}: {e}")+ raise ProcessingError(f"Failed to fetch URL: {e}") from e++ # Extract content and metadata+ html_content = response.text+ web_content = self.extract_content(html_content, url=url)+ web_content.status_code = response.status_code++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Ingested {url} ({response.status_code})")+ self.logger.debug(+ f"Ingested URL: {url}, status={response.status_code}, "+ f"text_length={len(web_content.text)}, links={len(web_content.links)}"+ )++ return web_content++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef crawl_sitemap(self,@@ -642,48 +662,65 @@ class WebIngestor:Raises:ProcessingError: If sitemap cannot be parsed or fail_fast=True and error occurs"""- crawler = SitemapCrawler(**self.config)+ # Track sitemap crawling+ tracking_id = self.progress_tracker.start_tracking(+ file=sitemap_url,+ module="ingest",+ submodule="WebIngestor",+ message=f"Sitemap: {sitemap_url}"+ )- # Parse sitemap (try as regular sitemap first, then as index)try:- urls = crawler.parse_sitemap(sitemap_url)- except Exception as e:- # Try as sitemap index- try:- urls = crawler.crawl_sitemap_index(sitemap_url)- except Exception:- raise ProcessingError(f"Failed to parse sitemap: {e}") from e-- self.logger.debug(f"Found {len(urls)} URL(s) in sitemap: {sitemap_url}")-- # Apply URL filters- if filters:- urls = self._apply_url_filters(urls, filters)- self.logger.debug(f"After filtering: {len(urls)} URL(s)")-- # Process each URL- web_contents = []- max_urls = max_urls or filters.get('max_urls') or self.config.get('max_urls')-- for idx, url in enumerate(urls):- if max_urls and idx >= max_urls:- self.logger.debug(f"Reached max_urls limit ({max_urls}), stopping crawl")- break+ crawler = SitemapCrawler(**self.config)+ # Parse sitemap (try as regular sitemap first, then as index)try:- web_content = self.ingest_url(url)- web_contents.append(web_content)- self.logger.debug(f"Crawled URL {idx+1}/{min(len(urls), max_urls or len(urls))}: {url}")+ urls = crawler.parse_sitemap(sitemap_url)except Exception as e:- self.logger.error(f"Failed to crawl URL {url}: {e}")- if fail_fast or self.config.get('fail_fast', False):- raise ProcessingError(f"Failed to crawl URL: {e}") from e-- self.logger.info(- f"Crawled {len(web_contents)}/{len(urls)} URL(s) from sitemap: {sitemap_url}"- )-- return web_contents+ # Try as sitemap index+ try:+ urls = crawler.crawl_sitemap_index(sitemap_url)+ except Exception:+ raise ProcessingError(f"Failed to parse sitemap: {e}") from e++ self.logger.debug(f"Found {len(urls)} URL(s) in sitemap: {sitemap_url}")++ # Apply URL filters+ if filters:+ urls = self._apply_url_filters(urls, filters)+ self.logger.debug(f"After filtering: {len(urls)} URL(s)")++ # Process each URL+ web_contents = []+ max_urls = max_urls or filters.get('max_urls') or self.config.get('max_urls')++ self.progress_tracker.update_tracking(tracking_id, message=f"Crawling {len(urls)} URLs")++ for idx, url in enumerate(urls):+ if max_urls and idx >= max_urls:+ self.logger.debug(f"Reached max_urls limit ({max_urls}), stopping crawl")+ break++ try:+ web_content = self.ingest_url(url)+ web_contents.append(web_content)+ self.logger.debug(f"Crawled URL {idx+1}/{min(len(urls), max_urls or len(urls))}: {url}")+ except Exception as e:+ self.logger.error(f"Failed to crawl URL {url}: {e}")+ if fail_fast or self.config.get('fail_fast', False):+ raise ProcessingError(f"Failed to crawl URL: {e}") from e++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Crawled {len(web_contents)}/{len(urls)} URLs")+ self.logger.info(+ f"Crawled {len(web_contents)}/{len(urls)} URL(s) from sitemap: {sitemap_url}"+ )++ return web_contents++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef crawl_domain(self,diff --git a/semantica/kg/graph_builder.py b/semantica/kg/graph_builder.pyindex 39bd45eb..4f47e067 100644--- a/semantica/kg/graph_builder.py+++ b/semantica/kg/graph_builder.py@@ -87,7 +87,9 @@ class GraphBuilder:# Initialize loggingfrom ..utils.logging import get_logger+ from ..utils.progress_tracker import get_progress_trackerself.logger = get_logger("graph_builder")+ self.progress_tracker = get_progress_tracker()# Initialize entity resolver if entity merging is enabled# This helps deduplicate and merge similar entities@@ -153,94 +155,108 @@ class GraphBuilder:if not isinstance(sources, list):sources = [sources]- self.logger.info(f"Building knowledge graph from {len(sources)} source(s)")-- # Use provided resolver or default instance resolver- resolver_to_use = entity_resolver or self.entity_resolver-- # Extract entities and relationships from all sources- all_entities = []- all_relationships = []-- for source in sources:- if isinstance(source, dict):- # Source is a dictionary - extract entities and relationships- if "entities" in source:- # Explicit entities list- all_entities.extend(source["entities"])- elif "id" in source or "entity_id" in source:- # Single entity object- all_entities.append(source)-- if "relationships" in source:- # Explicit relationships list- all_relationships.extend(source["relationships"])- elif "source" in source and "target" in source:- # Single relationship object- all_relationships.append(source)-- elif isinstance(source, list):- # Source is a list - process each item- for item in source:- if isinstance(item, dict):- # Determine if item is a relationship or entity- if "source" in item and "target" in item:- all_relationships.append(item)- else:- all_entities.append(item)-- self.logger.debug(- f"Extracted {len(all_entities)} entities and "- f"{len(all_relationships)} relationships from sources"+ # Track graph building+ tracking_id = self.progress_tracker.start_tracking(+ module="kg",+ submodule="GraphBuilder",+ message=f"Knowledge graph from {len(sources)} source(s)")- # Resolve entities (deduplicate and merge) if resolver is available- resolved_entities = all_entities- if resolver_to_use and all_entities:- self.logger.info(f"Resolving {len(all_entities)} entities using {self.entity_resolution_strategy} strategy")- resolved_entities = resolver_to_use.resolve_entities(all_entities)- self.logger.info(- f"Entity resolution complete: {len(all_entities)} -> {len(resolved_entities)} unique entities"+ try:+ self.logger.info(f"Building knowledge graph from {len(sources)} source(s)")++ # Use provided resolver or default instance resolver+ resolver_to_use = entity_resolver or self.entity_resolver++ # Extract entities and relationships from all sources+ all_entities = []+ all_relationships = []++ for source in sources:+ if isinstance(source, dict):+ # Source is a dictionary - extract entities and relationships+ if "entities" in source:+ # Explicit entities list+ all_entities.extend(source["entities"])+ elif "id" in source or "entity_id" in source:+ # Single entity object+ all_entities.append(source)++ if "relationships" in source:+ # Explicit relationships list+ all_relationships.extend(source["relationships"])+ elif "source" in source and "target" in source:+ # Single relationship object+ all_relationships.append(source)++ elif isinstance(source, list):+ # Source is a list - process each item+ for item in source:+ if isinstance(item, dict):+ # Determine if item is a relationship or entity+ if "source" in item and "target" in item:+ all_relationships.append(item)+ else:+ all_entities.append(item)++ self.logger.debug(+ f"Extracted {len(all_entities)} entities and "+ f"{len(all_relationships)} relationships from sources")-- # Build graph structure- graph = {- "entities": resolved_entities,- "relationships": all_relationships,- "metadata": {- "num_entities": len(resolved_entities),- "num_relationships": len(all_relationships),- "temporal_enabled": self.enable_temporal,- "timestamp": self._get_timestamp(),- "entity_resolution_applied": resolver_to_use is not None++ # Resolve entities (deduplicate and merge) if resolver is available+ resolved_entities = all_entities+ if resolver_to_use and all_entities:+ self.logger.info(f"Resolving {len(all_entities)} entities using {self.entity_resolution_strategy} strategy")+ resolved_entities = resolver_to_use.resolve_entities(all_entities)+ self.logger.info(+ f"Entity resolution complete: {len(all_entities)} -> {len(resolved_entities)} unique entities"+ )++ # Build graph structure+ graph = {+ "entities": resolved_entities,+ "relationships": all_relationships,+ "metadata": {+ "num_entities": len(resolved_entities),+ "num_relationships": len(all_relationships),+ "temporal_enabled": self.enable_temporal,+ "timestamp": self._get_timestamp(),+ "entity_resolution_applied": resolver_to_use is not None+ }}- }-- # Detect and resolve conflicts if conflict detector is available- if self.conflict_detector:- self.logger.debug("Detecting conflicts in graph")- detected_conflicts = self.conflict_detector.detect_conflicts(graph)- if detected_conflicts:- conflict_count = len(detected_conflicts)- self.logger.warning(f"Detected {conflict_count} conflict(s) in graph")-- # Attempt to resolve conflicts- resolution_result = self.conflict_detector.resolve_conflicts(detected_conflicts)- resolved_count = resolution_result.get('resolved_count', 0)+ # Detect and resolve conflicts if conflict detector is available+ if self.conflict_detector:+ self.logger.debug("Detecting conflicts in graph")+ detected_conflicts = self.conflict_detector.detect_conflicts(graph)- if resolved_count > 0:- self.logger.info(f"Successfully resolved {resolved_count} out of {conflict_count} conflict(s)")- else:- self.logger.warning("No conflicts were automatically resolved")-- # Log final graph statistics- self.logger.info(- f"Knowledge graph built successfully: "- f"{len(resolved_entities)} entities, {len(all_relationships)} relationships"- )+ if detected_conflicts:+ conflict_count = len(detected_conflicts)+ self.logger.warning(f"Detected {conflict_count} conflict(s) in graph")++ # Attempt to resolve conflicts+ resolution_result = self.conflict_detector.resolve_conflicts(detected_conflicts)+ resolved_count = resolution_result.get('resolved_count', 0)++ if resolved_count > 0:+ self.logger.info(f"Successfully resolved {resolved_count} out of {conflict_count} conflict(s)")+ else:+ self.logger.warning("No conflicts were automatically resolved")- return graph+ # Log final graph statistics+ self.logger.info(+ f"Knowledge graph built successfully: "+ f"{len(resolved_entities)} entities, {len(all_relationships)} relationships"+ )++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Built graph with {len(resolved_entities)} entities, {len(all_relationships)} relationships")+ return graph++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef add_temporal_edge(self,diff --git a/semantica/parse/code_parser.py b/semantica/parse/code_parser.pyindex b6500338..7257a2d6 100644--- a/semantica/parse/code_parser.py+++ b/semantica/parse/code_parser.py@@ -41,6 +41,7 @@ from typing import Any, Dict, List, Optional, Unionfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -95,6 +96,9 @@ class CodeParser:self.comment_extractor = CommentExtractor(**self.config.get("comments", {}))self.dependency_analyzer = DependencyAnalyzer(**self.config.get("dependencies", {}))+ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()+# Supported languagesself.supported_languages = {'.py': 'python',@@ -123,41 +127,58 @@ class CodeParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Code file not found: {file_path}")-- # Detect language if not specified- if language is None:- language = self._detect_language(file_path)-- if language not in self.supported_languages.values():- self.logger.warning(f"Language {language} may not be fully supported")+ # Track code parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="CodeParser",+ message=f"Code: {file_path.name}"+ )try:- # Read code content- with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:- code_content = f.read()-- # Extract structure- structure = self.extract_structure(code_content, language)+ if not file_path.exists():+ raise ValidationError(f"Code file not found: {file_path}")- # Extract comments- comments = self.extract_comments(code_content, language)+ # Detect language if not specified+ if language is None:+ language = self._detect_language(file_path)- # Analyze dependencies- dependencies = self.analyze_dependencies(code_content, language)-- return {- "file_path": str(file_path),- "language": language,- "structure": structure.__dict__,- "comments": [c.__dict__ for c in comments],- "dependencies": dependencies,- "line_count": len(code_content.splitlines()),- "size": len(code_content)- }+ if language not in self.supported_languages.values():+ self.logger.warning(f"Language {language} may not be fully supported")+ try:+ # Read code content+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:+ code_content = f.read()++ # Extract structure+ self.progress_tracker.update_tracking(tracking_id, message=f"Analyzing {language} code...")+ structure = self.extract_structure(code_content, language)++ # Extract comments+ comments = self.extract_comments(code_content, language)++ # Analyze dependencies+ dependencies = self.analyze_dependencies(code_content, language)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {language} code: {len(structure.functions)} functions, {len(structure.classes)} classes")+ return {+ "file_path": str(file_path),+ "language": language,+ "structure": structure.__dict__,+ "comments": [c.__dict__ for c in comments],+ "dependencies": dependencies,+ "line_count": len(code_content.splitlines()),+ "size": len(code_content)+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raise+except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))self.logger.error(f"Failed to parse code {file_path}: {e}")raise ProcessingError(f"Failed to parse code: {e}")diff --git a/semantica/parse/csv_parser.py b/semantica/parse/csv_parser.pyindex 495d6491..42cb2fc6 100644--- a/semantica/parse/csv_parser.py+++ b/semantica/parse/csv_parser.py@@ -34,6 +34,7 @@ from typing import Any, Dict, List, Optional, Unionfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -58,6 +59,7 @@ class CSVParser:"""self.logger = get_logger("csv_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self,@@ -133,24 +135,31 @@ class CSVParser:rows.append(row)else:rows.append(dict(zip(headers, row if isinstance(row, list) else [row])))-- metadata = {- "file_path": str(file_path),- "delimiter": delimiter,- "encoding": encoding,- "has_header": has_header- }-- return CSVData(- headers=headers,- rows=rows,- row_count=len(rows),- metadata=metadata- )-++ metadata = {+ "file_path": str(file_path),+ "delimiter": delimiter,+ "encoding": encoding,+ "has_header": has_header+ }++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {len(rows)} rows")+ return CSVData(+ headers=headers,+ rows=rows,+ row_count=len(rows),+ metadata=metadata+ )++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse CSV {file_path}: {e}")+ raise ProcessingError(f"Failed to parse CSV: {e}")+except Exception as e:- self.logger.error(f"Failed to parse CSV {file_path}: {e}")- raise ProcessingError(f"Failed to parse CSV: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef parse_to_dict(self, file_path: Union[str, Path], **options) -> List[Dict[str, Any]]:"""diff --git a/semantica/parse/document_parser.py b/semantica/parse/document_parser.pyindex 15b01805..f0b36f35 100644--- a/semantica/parse/document_parser.py+++ b/semantica/parse/document_parser.py@@ -33,6 +33,7 @@ from typing import Any, Dict, List, Optional, Unionfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom .pdf_parser import PDFParserfrom .docx_parser import DOCXParserfrom .html_parser import HTMLParser@@ -92,6 +93,9 @@ class DocumentParser:'.txt': 'text','.text': 'text'}++ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()def parse_document(self, file_path: Union[str, Path], file_type: Optional[str] = None, **options) -> Dict[str, Any]:"""@@ -114,29 +118,49 @@ class DocumentParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Document file not found: {file_path}")-- # Detect file type if not specified- if file_type is None:- file_type = self._detect_file_type(file_path)+ # Track document parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="DocumentParser",+ message=f"Document: {file_path.name}"+ )- # Route to appropriate parsertry:- if file_type == 'pdf':- return self.pdf_parser.parse(file_path, **options)- elif file_type == 'docx':- return self.docx_parser.parse(file_path, **options)- elif file_type == 'html':- return self.html_parser.parse(file_path, **options)- elif file_type == 'text':- return self._parse_text(file_path, **options)- else:- raise ValidationError(f"Unsupported document format: {file_type}")+ if not file_path.exists():+ raise ValidationError(f"Document file not found: {file_path}")++ # Detect file type if not specified+ if file_type is None:+ file_type = self._detect_file_type(file_path)++ self.progress_tracker.update_tracking(tracking_id, message=f"Parsing {file_type} document")++ # Route to appropriate parser+ try:+ if file_type == 'pdf':+ result = self.pdf_parser.parse(file_path, **options)+ elif file_type == 'docx':+ result = self.docx_parser.parse(file_path, **options)+ elif file_type == 'html':+ result = self.html_parser.parse(file_path, **options)+ elif file_type == 'text':+ result = self._parse_text(file_path, **options)+ else:+ raise ValidationError(f"Unsupported document format: {file_type}")++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {file_path.name} ({file_type})")+ return result++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse document {file_path}: {e}")+ raise ProcessingError(f"Failed to parse document: {e}")except Exception as e:- self.logger.error(f"Failed to parse document {file_path}: {e}")- raise ProcessingError(f"Failed to parse document: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_text(self, file_path: Union[str, Path], **options) -> str:"""diff --git a/semantica/parse/docx_parser.py b/semantica/parse/docx_parser.pyindex 6d0df0d3..43527010 100644--- a/semantica/parse/docx_parser.py+++ b/semantica/parse/docx_parser.py@@ -41,6 +41,7 @@ from docx.text.paragraph import Paragraphfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -81,6 +82,7 @@ class DOCXParser:"""self.logger = get_logger("docx_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:"""@@ -98,59 +100,75 @@ class DOCXParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"DOCX file not found: {file_path}")-- if not file_path.suffix.lower() in ['.docx', '.doc']:- raise ValidationError(f"File is not a DOCX: {file_path}")+ # Track DOCX parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="DOCXParser",+ message=f"DOCX: {file_path.name}"+ )try:- doc = Document(str(file_path))-- # Extract metadata- metadata = self._extract_metadata(doc)-- # Extract paragraphs- paragraphs = []- for para in doc.paragraphs:- if para.text.strip():- paragraphs.append(para.text.strip())+ if not file_path.exists():+ raise ValidationError(f"DOCX file not found: {file_path}")- # Extract tables- tables = []- if options.get("extract_tables", True):- for table in doc.tables:- table_data = self._extract_table(table)- tables.append(table_data)-- # Extract structure- sections = self._extract_sections(doc, options)-- # Extract comments if requested- comments = []- if options.get("extract_comments", False):- comments = self._extract_comments(doc)-- # Extract formatting if requested- formatting_info = None- if options.get("extract_formatting", False):- formatting_info = self._extract_formatting(doc)-- return {- "metadata": metadata.__dict__,- "full_text": "\n\n".join(paragraphs),- "paragraphs": paragraphs,- "tables": tables,- "sections": [s.__dict__ for s in sections],- "comments": comments,- "formatting": formatting_info,- "total_paragraphs": len(paragraphs),- "total_tables": len(tables)- }+ if not file_path.suffix.lower() in ['.docx', '.doc']:+ raise ValidationError(f"File is not a DOCX: {file_path}")+ try:+ doc = Document(str(file_path))++ # Extract metadata+ metadata = self._extract_metadata(doc)++ # Extract paragraphs+ paragraphs = []+ for para in doc.paragraphs:+ if para.text.strip():+ paragraphs.append(para.text.strip())++ # Extract tables+ tables = []+ if options.get("extract_tables", True):+ for table in doc.tables:+ table_data = self._extract_table(table)+ tables.append(table_data)++ # Extract structure+ sections = self._extract_sections(doc, options)++ # Extract comments if requested+ comments = []+ if options.get("extract_comments", False):+ comments = self._extract_comments(doc)++ # Extract formatting if requested+ formatting_info = None+ if options.get("extract_formatting", False):+ formatting_info = self._extract_formatting(doc)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {len(paragraphs)} paragraphs, {len(tables)} tables")+ return {+ "metadata": metadata.__dict__,+ "full_text": "\n\n".join(paragraphs),+ "paragraphs": paragraphs,+ "tables": tables,+ "sections": [s.__dict__ for s in sections],+ "comments": comments,+ "formatting": formatting_info,+ "total_paragraphs": len(paragraphs),+ "total_tables": len(tables)+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse DOCX {file_path}: {e}")+ raise ProcessingError(f"Failed to parse DOCX: {e}")+except Exception as e:- self.logger.error(f"Failed to parse DOCX {file_path}: {e}")- raise ProcessingError(f"Failed to parse DOCX: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_text(self, file_path: Union[str, Path]) -> str:"""diff --git a/semantica/parse/email_parser.py b/semantica/parse/email_parser.pyindex b9c935bc..118ea28c 100644--- a/semantica/parse/email_parser.py+++ b/semantica/parse/email_parser.py@@ -42,6 +42,7 @@ from typing import Any, Dict, List, Optional, Unionfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -98,6 +99,7 @@ class EmailParser:self.mime_parser = MIMEParser(**self.config.get("mime", {}))self.thread_analyzer = EmailThreadAnalyzer(**self.config.get("thread", {}))+ self.progress_tracker = get_progress_tracker()def parse_email(self, email_content: Union[str, bytes, Path], **options) -> EmailData:"""@@ -111,39 +113,58 @@ class EmailParser:Returns:EmailData: Parsed email data"""- # Load email content+ # Track email parsing+ file_path = Noneif isinstance(email_content, Path) or (isinstance(email_content, str) and Path(email_content).exists()):file_path = Path(email_content)- if not file_path.exists():- raise ValidationError(f"Email file not found: {file_path}")-- with open(file_path, 'rb') as f:- email_bytes = f.read()- email_msg = message_from_bytes(email_bytes)- elif isinstance(email_content, bytes):- email_msg = message_from_bytes(email_content)- else:- email_msg = message_from_string(email_content)++ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path) if file_path else None,+ module="parse",+ submodule="EmailParser",+ message=f"Email: {file_path.name if file_path else 'content'}"+ )try:- # Extract headers- headers = self.extract_headers(email_msg)-- # Extract body- body = self.extract_body(email_msg, extract_attachments=options.get("extract_attachments", True))-- return EmailData(- headers=headers,- body=body,- metadata={- "message_id": headers.message_id,- "date": headers.date- }- )+ # Load email content+ if file_path:+ if not file_path.exists():+ raise ValidationError(f"Email file not found: {file_path}")++ with open(file_path, 'rb') as f:+ email_bytes = f.read()+ email_msg = message_from_bytes(email_bytes)+ elif isinstance(email_content, bytes):+ email_msg = message_from_bytes(email_content)+ else:+ email_msg = message_from_string(email_content)+ try:+ # Extract headers+ headers = self.extract_headers(email_msg)++ # Extract body+ body = self.extract_body(email_msg, extract_attachments=options.get("extract_attachments", True))++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed email: {headers.subject or 'No subject'}")+ return EmailData(+ headers=headers,+ body=body,+ metadata={+ "message_id": headers.message_id,+ "date": headers.date+ }+ )++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse email: {e}")+ raise ProcessingError(f"Failed to parse email: {e}")+except Exception as e:- self.logger.error(f"Failed to parse email: {e}")- raise ProcessingError(f"Failed to parse email: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_headers(self, email_message: email.message.Message) -> EmailHeaders:"""diff --git a/semantica/parse/excel_parser.py b/semantica/parse/excel_parser.pyindex 81c2cb7b..0a66837c 100644--- a/semantica/parse/excel_parser.py+++ b/semantica/parse/excel_parser.py@@ -71,6 +71,7 @@ class ExcelParser:"""self.logger = get_logger("excel_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self,@@ -95,23 +96,44 @@ class ExcelParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Excel file not found: {file_path}")-- if not file_path.suffix.lower() in ['.xlsx', '.xls', '.xlsm']:- raise ValidationError(f"File is not an Excel file: {file_path}")+ # Track Excel parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="ExcelParser",+ message=f"Excel: {file_path.name}"+ )try:- engine = options.get("engine", "pandas")+ if not file_path.exists():+ raise ValidationError(f"Excel file not found: {file_path}")- if engine == "pandas":- return self._parse_with_pandas(file_path, sheet_name, **options)- else:- return self._parse_with_openpyxl(file_path, sheet_name, **options)+ if not file_path.suffix.lower() in ['.xlsx', '.xls', '.xlsm']:+ raise ValidationError(f"File is not an Excel file: {file_path}")++ try:+ engine = options.get("engine", "pandas")++ self.progress_tracker.update_tracking(tracking_id, message=f"Parsing with {engine}...")++ if engine == "pandas":+ result = self._parse_with_pandas(file_path, sheet_name, **options)+ else:+ result = self._parse_with_openpyxl(file_path, sheet_name, **options)++ sheet_count = len(result.sheets) if hasattr(result, 'sheets') else 1+ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {sheet_count} sheet(s)")+ return result++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse Excel {file_path}: {e}")+ raise ProcessingError(f"Failed to parse Excel: {e}")except Exception as e:- self.logger.error(f"Failed to parse Excel {file_path}: {e}")- raise ProcessingError(f"Failed to parse Excel: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef _parse_with_pandas(self,diff --git a/semantica/parse/html_parser.py b/semantica/parse/html_parser.pyindex 305469fe..4fac812b 100644--- a/semantica/parse/html_parser.py+++ b/semantica/parse/html_parser.py@@ -77,6 +77,7 @@ class HTMLParser:"""self.logger = get_logger("html_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self, html_content: Union[str, Path], base_url: Optional[str] = None, **options) -> Dict[str, Any]:"""@@ -95,62 +96,82 @@ class HTMLParser:Returns:dict: Parsed HTML data"""- # Load HTML content+ # Track HTML parsing+ file_path = Noneif isinstance(html_content, Path) or (isinstance(html_content, str) and Path(html_content).exists()):- with open(html_content, 'r', encoding='utf-8', errors='ignore') as f:- html_string = f.read()- else:- html_string = html_content+ file_path = Path(html_content)++ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path) if file_path else None,+ module="parse",+ submodule="HTMLParser",+ message=f"HTML: {file_path.name if file_path else 'content'}"+ )try:- soup = BeautifulSoup(html_string, 'html.parser')-- # Extract metadata- metadata = self._extract_metadata(soup)-- # Extract text content- if options.get("clean_text", True):- text = self._extract_clean_text(soup)+ # Load HTML content+ if file_path:+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:+ html_string = f.read()else:- text = soup.get_text()-- # Extract links- links = []- if options.get("extract_links", True):- links = self._extract_links(soup, base_url)-- # Extract images- images = []- if options.get("extract_images", True):- images = self._extract_images(soup, base_url)-- # Extract forms- forms = []- if options.get("extract_forms", False):- forms = self._extract_forms(soup)-- # Extract tables- tables = []- if options.get("extract_tables", True):- tables = self._extract_tables(soup)-- # Extract structure- structure = self._extract_structure(soup)-- return {- "metadata": metadata.__dict__,- "text": text,- "html": html_string,- "links": links,- "images": images,- "forms": forms,- "tables": tables,- "structure": structure- }+ html_string = html_content+ try:+ soup = BeautifulSoup(html_string, 'html.parser')++ # Extract metadata+ metadata = self._extract_metadata(soup)++ # Extract text content+ if options.get("clean_text", True):+ text = self._extract_clean_text(soup)+ else:+ text = soup.get_text()++ # Extract links+ links = []+ if options.get("extract_links", True):+ links = self._extract_links(soup, base_url)++ # Extract images+ images = []+ if options.get("extract_images", True):+ images = self._extract_images(soup, base_url)++ # Extract forms+ forms = []+ if options.get("extract_forms", False):+ forms = self._extract_forms(soup)++ # Extract tables+ tables = []+ if options.get("extract_tables", True):+ tables = self._extract_tables(soup)++ # Extract structure+ structure = self._extract_structure(soup)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed HTML: {len(links)} links, {len(images)} images")+ return {+ "metadata": metadata.__dict__,+ "text": text,+ "html": html_string,+ "links": links,+ "images": images,+ "forms": forms,+ "tables": tables,+ "structure": structure+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse HTML: {e}")+ raise ProcessingError(f"Failed to parse HTML: {e}")+except Exception as e:- self.logger.error(f"Failed to parse HTML: {e}")- raise ProcessingError(f"Failed to parse HTML: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_text(self, html_content: Union[str, Path], clean: bool = True) -> str:"""diff --git a/semantica/parse/image_parser.py b/semantica/parse/image_parser.pyindex f7f920c1..fcecc70b 100644--- a/semantica/parse/image_parser.py+++ b/semantica/parse/image_parser.py@@ -37,6 +37,7 @@ from PIL.Image import Image as PILImagefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackertry:import pytesseract@@ -80,6 +81,7 @@ class ImageParser:"""self.logger = get_logger("image_parser")self.config = config+ self.progress_tracker = get_progress_tracker()self.tesseract_path = config.get("tesseract_path")if self.tesseract_path:pytesseract.pytesseract.tesseract_cmd = self.tesseract_path@@ -100,37 +102,55 @@ class ImageParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Image file not found: {file_path}")-- # Validate image file- try:- with Image.open(file_path) as img:- img.verify()- except Exception as e:- raise ValidationError(f"Invalid image file: {e}")+ # Track image parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="ImageParser",+ message=f"Image: {file_path.name}"+ )try:- with Image.open(file_path) as img:- # Extract metadata- metadata = None- if options.get("extract_metadata", True):- metadata = self._extract_metadata(img, file_path)-- # Extract text using OCR- ocr_result = None- if options.get("extract_text", False) and TESSERACT_AVAILABLE:- ocr_result = self.extract_text(file_path, language=options.get("ocr_language", "eng"))-- return {- "metadata": metadata.__dict__ if metadata else None,- "ocr": ocr_result.__dict__ if ocr_result else None,- "text": ocr_result.text if ocr_result else None- }+ if not file_path.exists():+ raise ValidationError(f"Image file not found: {file_path}")++ # Validate image file+ try:+ with Image.open(file_path) as img:+ img.verify()+ except Exception as e:+ raise ValidationError(f"Invalid image file: {e}")++ try:+ with Image.open(file_path) as img:+ # Extract metadata+ metadata = None+ if options.get("extract_metadata", True):+ self.progress_tracker.update_tracking(tracking_id, message="Extracting metadata...")+ metadata = self._extract_metadata(img, file_path)++ # Extract text using OCR+ ocr_result = None+ if options.get("extract_text", False) and TESSERACT_AVAILABLE:+ self.progress_tracker.update_tracking(tracking_id, message="Running OCR...")+ ocr_result = self.extract_text(file_path, language=options.get("ocr_language", "eng"))++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message="Image parsed successfully")+ return {+ "metadata": metadata.__dict__ if metadata else None,+ "ocr": ocr_result.__dict__ if ocr_result else None,+ "text": ocr_result.text if ocr_result else None+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse image {file_path}: {e}")+ raise ProcessingError(f"Failed to parse image: {e}")except Exception as e:- self.logger.error(f"Failed to parse image {file_path}: {e}")- raise ProcessingError(f"Failed to parse image: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_text(self, file_path: Union[str, Path], language: str = "eng", **options) -> OCRResult:"""diff --git a/semantica/parse/json_parser.py b/semantica/parse/json_parser.pyindex 0f14ee68..87dc0a89 100644--- a/semantica/parse/json_parser.py+++ b/semantica/parse/json_parser.py@@ -34,6 +34,7 @@ from typing import Any, Dict, List, Optional, Unionfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -57,6 +58,7 @@ class JSONParser:"""self.logger = get_logger("json_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self, file_path: Union[str, Path], **options) -> JSONData:"""@@ -72,51 +74,69 @@ class JSONParser:Returns:JSONData: Parsed JSON data"""- encoding = options.get("encoding", "utf-8")-- # Check if input is a file path or JSON string+ # Track JSON parsing+ file_path_obj = Noneif isinstance(file_path, Path) or (isinstance(file_path, str) and Path(file_path).exists()):file_path_obj = Path(file_path)- if not file_path_obj.exists():- raise ValidationError(f"JSON file not found: {file_path_obj}")-- try:- with open(file_path_obj, 'r', encoding=encoding) as f:- data = json.load(f)- source = str(file_path_obj)- except json.JSONDecodeError as e:- raise ValidationError(f"Invalid JSON file: {e}")- else:- # Assume it's a JSON string- try:- data = json.loads(file_path)- source = "string"- except json.JSONDecodeError as e:- raise ValidationError(f"Invalid JSON string: {e}")-- # Determine data type- data_type = self._determine_type(data)- # Flatten if requested- if options.get("flatten", False):- data = self._flatten(data)-- # Extract paths if requested- paths = None- if options.get("extract_paths", False):- paths = self._extract_paths(data)-- metadata = {- "source": source,- "type": data_type,- "paths": paths- }-- return JSONData(- data=data,- type=data_type,- metadata=metadata+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path_obj) if file_path_obj else None,+ module="parse",+ submodule="JSONParser",+ message=f"JSON: {file_path_obj.name if file_path_obj else 'content'}")++ try:+ encoding = options.get("encoding", "utf-8")++ # Check if input is a file path or JSON string+ if file_path_obj:+ if not file_path_obj.exists():+ raise ValidationError(f"JSON file not found: {file_path_obj}")++ try:+ with open(file_path_obj, 'r', encoding=encoding) as f:+ data = json.load(f)+ source = str(file_path_obj)+ except json.JSONDecodeError as e:+ raise ValidationError(f"Invalid JSON file: {e}")+ else:+ # Assume it's a JSON string+ try:+ data = json.loads(file_path)+ source = "string"+ except json.JSONDecodeError as e:+ raise ValidationError(f"Invalid JSON string: {e}")++ # Determine data type+ data_type = self._determine_type(data)++ # Flatten if requested+ if options.get("flatten", False):+ data = self._flatten(data)++ # Extract paths if requested+ paths = None+ if options.get("extract_paths", False):+ paths = self._extract_paths(data)++ metadata = {+ "source": source,+ "type": data_type,+ "paths": paths+ }++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed JSON ({data_type})")+ return JSONData(+ data=data,+ type=data_type,+ metadata=metadata+ )++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef parse_to_dict(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:"""diff --git a/semantica/parse/media_parser.py b/semantica/parse/media_parser.pyindex 4008c671..3d56cb64 100644--- a/semantica/parse/media_parser.py+++ b/semantica/parse/media_parser.py@@ -32,6 +32,7 @@ from typing import Any, Dict, List, Optional, Unionfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom .image_parser import ImageParser@@ -93,21 +94,40 @@ class MediaParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"Media file not found: {file_path}")+ # Track media parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="MediaParser",+ message=f"Media: {file_path.name}"+ )- # Detect media type if not specified- if media_type is None:- media_type = self._detect_media_type(file_path)-- if media_type == "image":- return self.image_parser.parse(file_path, **options)- elif media_type == "audio":- return self._parse_audio(file_path, **options)- elif media_type == "video":- return self._parse_video(file_path, **options)- else:- raise ValidationError(f"Unsupported media type: {media_type}")+ try:+ if not file_path.exists():+ raise ValidationError(f"Media file not found: {file_path}")++ # Detect media type if not specified+ if media_type is None:+ media_type = self._detect_media_type(file_path)++ self.progress_tracker.update_tracking(tracking_id, message=f"Parsing {media_type}...")++ if media_type == "image":+ result = self.image_parser.parse(file_path, **options)+ elif media_type == "audio":+ result = self._parse_audio(file_path, **options)+ elif media_type == "video":+ result = self._parse_video(file_path, **options)+ else:+ raise ValidationError(f"Unsupported media type: {media_type}")++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {media_type} successfully")+ return result++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_metadata(self, file_path: Union[str, Path], media_type: Optional[str] = None) -> Dict[str, Any]:"""diff --git a/semantica/parse/pdf_parser.py b/semantica/parse/pdf_parser.pyindex 9c68df4f..2a62a685 100644--- a/semantica/parse/pdf_parser.py+++ b/semantica/parse/pdf_parser.py@@ -38,6 +38,7 @@ from PIL import Imagefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -78,6 +79,7 @@ class PDFParser:"""self.logger = get_logger("pdf_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self, file_path: Union[str, Path], **options) -> Dict[str, Any]:"""@@ -96,41 +98,60 @@ class PDFParser:"""file_path = Path(file_path)- if not file_path.exists():- raise ValidationError(f"PDF file not found: {file_path}")-- if not file_path.suffix.lower() == '.pdf':- raise ValidationError(f"File is not a PDF: {file_path}")+ # Track PDF parsing+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path),+ module="parse",+ submodule="PDFParser",+ message=f"PDF: {file_path.name}"+ )try:- with pdfplumber.open(str(file_path)) as pdf:- # Extract metadata- metadata = self._extract_metadata(pdf)- metadata.page_count = len(pdf.pages)-- # Extract pages- pages = []- page_numbers = options.get("pages", range(len(pdf.pages)))-- for page_num in page_numbers:- if page_num < len(pdf.pages):- page_data = self._parse_page(- pdf.pages[page_num],- page_num + 1,- options- )- pages.append(page_data)-- return {- "metadata": metadata.__dict__,- "pages": [page.__dict__ for page in pages],- "full_text": "\n\n".join(page.text for page in pages),- "total_pages": len(pdf.pages)- }+ if not file_path.exists():+ raise ValidationError(f"PDF file not found: {file_path}")++ if not file_path.suffix.lower() == '.pdf':+ raise ValidationError(f"File is not a PDF: {file_path}")++ try:+ with pdfplumber.open(str(file_path)) as pdf:+ # Extract metadata+ metadata = self._extract_metadata(pdf)+ metadata.page_count = len(pdf.pages)++ # Extract pages+ pages = []+ page_numbers = options.get("pages", range(len(pdf.pages)))++ self.progress_tracker.update_tracking(tracking_id,+ message=f"Parsing {len(pdf.pages)} pages")++ for page_num in page_numbers:+ if page_num < len(pdf.pages):+ page_data = self._parse_page(+ pdf.pages[page_num],+ page_num + 1,+ options+ )+ pages.append(page_data)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {len(pages)} pages")+ return {+ "metadata": metadata.__dict__,+ "pages": [page.__dict__ for page in pages],+ "full_text": "\n\n".join(page.text for page in pages),+ "total_pages": len(pdf.pages)+ }++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse PDF {file_path}: {e}")+ raise ProcessingError(f"Failed to parse PDF: {e}")except Exception as e:- self.logger.error(f"Failed to parse PDF {file_path}: {e}")- raise ProcessingError(f"Failed to parse PDF: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef extract_text(self, file_path: Union[str, Path], pages: Optional[List[int]] = None) -> str:"""diff --git a/semantica/parse/pptx_parser.py b/semantica/parse/pptx_parser.pyindex 57dabf57..a1262f8d 100644--- a/semantica/parse/pptx_parser.py+++ b/semantica/parse/pptx_parser.py@@ -36,6 +36,7 @@ from pptx import Presentationfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -71,6 +72,7 @@ class PPTXParser:"""self.logger = get_logger("pptx_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self, file_path: Union[str, Path], **options) -> PPTXData:"""diff --git a/semantica/parse/structured_data_parser.py b/semantica/parse/structured_data_parser.pyindex 8294d4a4..b98c8348 100644--- a/semantica/parse/structured_data_parser.py+++ b/semantica/parse/structured_data_parser.py@@ -34,6 +34,7 @@ import yamlfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom .csv_parser import CSVParserfrom .json_parser import JSONParserfrom .xml_parser import XMLParser@@ -74,21 +75,44 @@ class StructuredDataParser:Returns:dict: Parsed data"""- # Detect format if not specified- if data_format is None:- data_format = self._detect_format(data)+ # Track structured data parsing+ file_path = None+ if isinstance(data, Path) or (isinstance(data, str) and Path(data).exists()):+ file_path = Path(data)- # Route to appropriate parser- if data_format == "json":- return self.json_parser.parse(data, **options).__dict__- elif data_format == "csv":- return self.csv_parser.parse(data, **options).__dict__- elif data_format == "xml":- return self.xml_parser.parse(data, **options).__dict__- elif data_format == "yaml":- return self._parse_yaml(data, **options)- else:- raise ValidationError(f"Unsupported data format: {data_format}")+ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path) if file_path else None,+ module="parse",+ submodule="StructuredDataParser",+ message=f"Structured data: {file_path.name if file_path else 'content'}"+ )++ try:+ # Detect format if not specified+ if data_format is None:+ data_format = self._detect_format(data)++ self.progress_tracker.update_tracking(tracking_id, message=f"Parsing {data_format}...")++ # Route to appropriate parser+ if data_format == "json":+ result = self.json_parser.parse(data, **options).__dict__+ elif data_format == "csv":+ result = self.csv_parser.parse(data, **options).__dict__+ elif data_format == "xml":+ result = self.xml_parser.parse(data, **options).__dict__+ elif data_format == "yaml":+ result = self._parse_yaml(data, **options)+ else:+ raise ValidationError(f"Unsupported data format: {data_format}")++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message=f"Parsed {data_format} successfully")+ return result++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef validate_data(self, data: Any, schema: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:"""diff --git a/semantica/parse/web_parser.py b/semantica/parse/web_parser.pyindex 6f5c46d6..b0d5147d 100644--- a/semantica/parse/web_parser.py+++ b/semantica/parse/web_parser.py@@ -37,6 +37,7 @@ from bs4 import BeautifulSoupfrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom .html_parser import HTMLParserfrom .xml_parser import XMLParserdiff --git a/semantica/parse/xml_parser.py b/semantica/parse/xml_parser.pyindex 8c455be5..b4ef3772 100644--- a/semantica/parse/xml_parser.py+++ b/semantica/parse/xml_parser.py@@ -38,6 +38,7 @@ from lxml import etreefrom ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_tracker@dataclass@@ -72,6 +73,7 @@ class XMLParser:"""self.logger = get_logger("xml_parser")self.config = config+ self.progress_tracker = get_progress_tracker()def parse(self,@@ -92,30 +94,51 @@ class XMLParser:Returns:XMLData: Parsed XML data"""- engine = options.get("engine", "lxml")-- # Load XML content+ # Track XML parsing+ file_path_obj = Noneif isinstance(file_path, Path) or (isinstance(file_path, str) and Path(file_path).exists()):file_path_obj = Path(file_path)- if not file_path_obj.exists():- raise ValidationError(f"XML file not found: {file_path_obj}")-- with open(file_path_obj, 'r', encoding='utf-8', errors='ignore') as f:- xml_string = f.read()- source = str(file_path_obj)- else:- xml_string = file_path- source = "string"++ tracking_id = self.progress_tracker.start_tracking(+ file=str(file_path_obj) if file_path_obj else None,+ module="parse",+ submodule="XMLParser",+ message=f"XML: {file_path_obj.name if file_path_obj else 'content'}"+ )try:- if engine == "lxml":- return self._parse_with_lxml(xml_string, source, options)+ engine = options.get("engine", "lxml")++ # Load XML content+ if file_path_obj:+ if not file_path_obj.exists():+ raise ValidationError(f"XML file not found: {file_path_obj}")++ with open(file_path_obj, 'r', encoding='utf-8', errors='ignore') as f:+ xml_string = f.read()+ source = str(file_path_obj)else:- return self._parse_with_etree(xml_string, source, options)+ xml_string = file_path+ source = "string"++ try:+ if engine == "lxml":+ result = self._parse_with_lxml(xml_string, source, options)+ else:+ result = self._parse_with_etree(xml_string, source, options)++ self.progress_tracker.stop_tracking(tracking_id, status="completed",+ message="Parsed XML successfully")+ return result++ except Exception as e:+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ self.logger.error(f"Failed to parse XML: {e}")+ raise ProcessingError(f"Failed to parse XML: {e}")except Exception as e:- self.logger.error(f"Failed to parse XML: {e}")- raise ProcessingError(f"Failed to parse XML: {e}")+ self.progress_tracker.stop_tracking(tracking_id, status="failed", message=str(e))+ raisedef _parse_with_lxml(self, xml_string: str, source: str, options: Dict[str, Any]) -> XMLData:"""Parse XML using lxml."""diff --git a/semantica/pipeline/execution_engine.py b/semantica/pipeline/execution_engine.pyindex 28a6d6e7..694602e4 100644--- a/semantica/pipeline/execution_engine.py+++ b/semantica/pipeline/execution_engine.py@@ -41,6 +41,7 @@ import timefrom ..utils.exceptions import ValidationError, ProcessingErrorfrom ..utils.logging import get_logger+from ..utils.progress_tracker import get_progress_trackerfrom .pipeline_builder import Pipeline, PipelineStep, StepStatusfrom .failure_handler import FailureHandlerfrom .parallelism_manager import ParallelismManager@@ -100,6 +101,9 @@ class ExecutionEngine:self.running_pipelines: Dict[str, Pipeline] = {}self.pipeline_status: Dict[str, PipelineStatus] = {}self.pipeline_lock = threading.Lock()++ # Initialize progress tracker+ self.progress_tracker = get_progress_tracker()def execute_pipeline(self,@@ -121,6 +125,13 @@ class ExecutionEngine:pipeline_id = pipeline.namestart_time = time.time()+ # Track pipeline execution+ pipeline_tracking_id = self.progress_tracker.start_tracking(+ module="pipeline",+ submodule="ExecutionEngine",+ message=f"Executing pipeline: {pipeline_id}"+ )+try:self.logger.info(f"Executing pipeline: {pipeline_id}")@@ -151,6 +162,13 @@ class ExecutionEngine:else:self.pipeline_status[pipeline_id] = PipelineStatus.FAILED+ # Update progress tracking+ self.progress_tracker.stop_tracking(+ pipeline_tracking_id,+ status="completed" if metrics["steps_failed"] == 0 else "failed",+ message=f"Executed {metrics['steps_executed']} steps in {execution_time:.2f}s"+ )+return ExecutionResult(success=metrics["steps_failed"] == 0,output=result,@@ -166,6 +184,7 @@ class ExecutionEngine:self.resource_scheduler.release_resources(resources)except Exception as e:+ self.progress_tracker.stop_tracking(pipeline_tracking_id, status="failed", message=str(e))self.logger.error(f"Pipeline execution failed: {e}")with self.pipeline_lock:self.pipeline_status[pipeline_id] = PipelineStatus.FAILED@@ -188,7 +207,9 @@ class ExecutionEngine:# Execute stepscurrent_data = data- for step in sorted_steps:+ total_steps = len(sorted_steps)++ for step_idx, step in enumerate(sorted_steps):if self.pipeline_status.get(pipeline.name) == PipelineStatus.STOPPED:break@@ -196,6 +217,13 @@ class ExecutionEngine:while self.pipeline_status.get(pipeline.name) == PipelineStatus.PAUSED:time.sleep(0.1)+ # Track step execution+ step_tracking_id = self.progress_tracker.start_tracking(+ module="pipeline",+ submodule=step.step_type or step.name,+ message=f"Step {step_idx + 1}/{total_steps}: {step.name}"+ )+try:# Execute stepstep.status = StepStatus.RUNNING@@ -204,6 +232,9 @@ class ExecutionEngine:step.result = step_resultcurrent_data = step_result+ self.progress_tracker.stop_tracking(step_tracking_id, status="completed",+ message=f"Completed step: {step.name}")+except Exception as e:step.status = StepStatus.FAILEDstep.error = e@@ -211,14 +242,19 @@ class ExecutionEngine:# Handle failurerecovery_result = self.failure_handler.handle_step_failure(step, e)if not recovery_result.get("retry", False):+ self.progress_tracker.stop_tracking(step_tracking_id, status="failed", message=str(e))raiseelse:# Retry step+ self.progress_tracker.update_tracking(step_tracking_id, status="running",+ message=f"Retrying step: {step.name}")step.status = StepStatus.RUNNINGstep_result = self._execute_step(step, current_data, **options)step.status = StepStatus.COMPLETEDstep.result = step_resultcurrent_data = step_result+ self.progress_tracker.stop_tracking(step_tracking_id, status="completed",+ message=f"Retry successful: {step.name}")return current_datadiff --git a/semantica/utils/__init__.py b/semantica/utils/__init__.pyindex 4b8558e1..95908ec9 100644--- a/semantica/utils/__init__.py+++ b/semantica/utils/__init__.py@@ -140,6 +140,17 @@ from .types import (relationship_to_dict,dict_to_relationship,)+from .progress_tracker import (+ ProgressTracker,+ ProgressDisplay,+ ConsoleProgressDisplay,+ JupyterProgressDisplay,+ FileProgressDisplay,+ ProgressItem,+ ModuleDetector,+ get_progress_tracker,+ track_progress,+)__all__ = [# Logging@@ -233,4 +244,14 @@ __all__ = ["dict_to_entity","relationship_to_dict","dict_to_relationship",+ # Progress Tracking+ "ProgressTracker",+ "ProgressDisplay",+ "ConsoleProgressDisplay",+ "JupyterProgressDisplay",+ "FileProgressDisplay",+ "ProgressItem",+ "ModuleDetector",+ "get_progress_tracker",+ "track_progress",]\ No newline at end of filediff --git a/semantica/utils/progress_tracker.py b/semantica/utils/progress_tracker.pynew file mode 100644index 00000000..ade10ab2--- /dev/null+++ b/semantica/utils/progress_tracker.py@@ -0,0 +1,1008 @@+"""+Progress Tracking Module++This module provides comprehensive progress tracking with visual indicators (emojis)+for file, module, and submodule processing across console, log files, and Jupyter notebooks.++Key Features:+ - Automatic module/submodule detection via introspection+ - Real-time progress updates with emojis+ - Console, Jupyter notebook, and log file support+ - Zero configuration required - works automatically+ - Final summary display++Main Classes:+ - ProgressTracker: Main tracking coordinator+ - ProgressDisplay: Abstract base class for displays+ - ConsoleProgressDisplay: Real-time console output+ - JupyterProgressDisplay: IPython/Jupyter notebook display+ - FileProgressDisplay: Log file progress tracking+ - track_progress: Decorator for automatic progress tracking++Example Usage:+ >>> from semantica.utils import track_progress+ >>>+ >>> @track_progress+ >>> def process_file(file_path):+ ... # Processing code - progress tracked automatically+ ... pass++Author: Semantica Contributors+License: MIT+"""++import sys+import inspect+import threading+import time+from abc import ABC, abstractmethod+from dataclasses import dataclass, field+from datetime import datetime+from typing import Any, Dict, List, Optional, Callable, Union, Tuple+from pathlib import Path+from contextlib import contextmanager++from .logging import get_logger++# Try to import IPython for Jupyter support+try:+ from IPython.display import display, clear_output, HTML+ from IPython import get_ipython+ IPYTHON_AVAILABLE = True+except ImportError:+ IPYTHON_AVAILABLE = False+++@dataclass+class ProgressItem:+ """Progress tracking item."""+ file: Optional[str] = None+ module: Optional[str] = None+ submodule: Optional[str] = None+ status: str = "pending" # pending, running, completed, failed+ start_time: Optional[float] = None+ end_time: Optional[float] = None+ message: str = ""+ emoji: str = "β³"+ metadata: Dict[str, Any] = field(default_factory=dict)+++class ProgressDisplay(ABC):+ """Abstract base class for progress displays."""++ @abstractmethod+ def update(self, item: ProgressItem) -> None:+ """Update progress display."""+ pass++ @abstractmethod+ def show_summary(self, items: List[ProgressItem]) -> None:+ """Show final summary."""+ pass++ @abstractmethod+ def clear(self) -> None:+ """Clear display."""+ pass+++class ConsoleProgressDisplay(ProgressDisplay):+ """Console progress display with real-time updates."""++ def __init__(self, use_emoji: bool = True, update_interval: float = 0.1):+ self.use_emoji = use_emoji+ self.update_interval = update_interval+ self.last_update = 0.0+ self.current_lines: Dict[str, str] = {}+ self.lock = threading.Lock()++ def _should_update(self) -> bool:+ """Check if enough time has passed for update."""+ now = time.time()+ if now - self.last_update >= self.update_interval:+ self.last_update = now+ return True+ return False++ def _get_emoji_for_module(self, module: str) -> str:+ """Get emoji for module type."""+ if not self.use_emoji:+ return ""++ emoji_map = {+ "ingest": "π₯",+ "parse": "π",+ "kg": "π§ ",+ "embeddings": "πΎ",+ "normalize": "π§",+ "ontology": "π",+ "semantic_extract": "π―",+ "seed": "π±",+ "split": "βοΈ",+ "triple_store": "ποΈ",+ "vector_store": "π",+ "export": "πΎ",+ "reasoning": "π€",+ "kg_qa": "β ",+ "visualization": "π",+ "context": "π",+ "conflicts": "β οΈ",+ "deduplication": "π",+ "pipeline": "βοΈ",+ }++ # Check if module name contains any key+ module_lower = module.lower()+ for key, emoji in emoji_map.items():+ if key in module_lower:+ return emoji++ return "β³"++ def _get_status_emoji(self, status: str) -> str:+ """Get emoji for status."""+ if not self.use_emoji:+ return ""++ status_map = {+ "pending": "β³",+ "running": "π",+ "completed": "β ",+ "failed": "β",+ }+ return status_map.get(status, "β³")++ def _get_action_message(self, module: Optional[str], message: str) -> str:+ """Get action message based on module."""+ # Extract action from message if it contains "Semantica:"+ if message and "Semantica:" in message:+ # Use the message as-is if it already has Semantica format+ return message.split("Semantica:")[-1].strip() if "Semantica:" in message else message++ # Map modules to actions+ action_map = {+ "ingest": "is ingesting",+ "parse": "is parsing",+ "kg": "is building",+ "embeddings": "is embedding",+ "normalize": "is normalizing",+ "ontology": "is generating",+ "semantic_extract": "is extracting",+ "seed": "is seeding",+ "split": "is splitting",+ "triple_store": "is storing",+ "vector_store": "is indexing",+ "export": "is exporting",+ "reasoning": "is reasoning",+ "kg_qa": "is validating",+ "visualization": "is visualizing",+ "context": "is processing",+ "conflicts": "is resolving",+ "deduplication": "is deduplicating",+ "pipeline": "is executing",+ "core": "is processing",+ }++ action = action_map.get(module or "", "is processing")+ return f"Semantica {action}"++ def update(self, item: ProgressItem) -> None:+ """Update console progress display."""+ if not self._should_update():+ return++ with self.lock:+ key = f"{item.module}:{item.submodule}"+ if item.file:+ key = f"{item.file}:{key}"++ # Build progress line+ parts = []++ # Semantica branding with action+ if self.use_emoji:+ parts.append("π§ ")++ # Create action message based on module+ action_msg = self._get_action_message(item.module, item.message)+ parts.append(action_msg)++ # Status emoji+ if self.use_emoji:+ parts.append(self._get_status_emoji(item.status))++ # Module emoji+ if item.module and self.use_emoji:+ parts.append(self._get_emoji_for_module(item.module))++ # Module name+ if item.module:+ parts.append(f"[{item.module}]")++ # Submodule+ if item.submodule:+ parts.append(f"{item.submodule}")++ # File+ if item.file:+ file_name = Path(item.file).name if item.file else ""+ parts.append(f"π {file_name}")++ # Time elapsed+ if item.start_time:+ elapsed = time.time() - item.start_time+ parts.append(f"({elapsed:.1f}s)")++ line = " ".join(parts)+ self.current_lines[key] = line++ # Print all current lines (overwrite previous)+ sys.stdout.write("\r" + " " * 100 + "\r") # Clear line+ if len(self.current_lines) == 1:+ sys.stdout.write(line)+ else:+ # Multiple items - show all+ lines_list = list(self.current_lines.values())+ sys.stdout.write("\n".join(lines_list[-3:])) # Show last 3+ sys.stdout.flush()++ def show_summary(self, items: List[ProgressItem]) -> None:+ """Show final summary."""+ with self.lock:+ # Clear current display+ sys.stdout.write("\n" + "=" * 80 + "\n")++ # Summary header+ if self.use_emoji:+ sys.stdout.write("π§ Semantica - π Progress Summary\n")+ else:+ sys.stdout.write("Semantica - Progress Summary\n")+ sys.stdout.write("=" * 80 + "\n")++ # Group by module+ by_module: Dict[str, List[ProgressItem]] = {}+ for item in items:+ module = item.module or "unknown"+ if module not in by_module:+ by_module[module] = []+ by_module[module].append(item)++ # Show summary by module+ total_time = 0.0+ completed = 0+ failed = 0++ for module, module_items in by_module.items():+ if self.use_emoji:+ emoji = self._get_emoji_for_module(module)+ sys.stdout.write(f"\n{emoji} {module.upper()}\n")+ else:+ sys.stdout.write(f"\n{module.upper()}\n")+ sys.stdout.write("-" * 80 + "\n")++ for item in module_items:+ status_emoji = self._get_status_emoji(item.status)+ duration = ""+ if item.start_time and item.end_time:+ duration = f" ({item.end_time - item.start_time:.2f}s)"+ elif item.start_time:+ duration = f" (running...)"++ line = f" {status_emoji} {item.submodule or 'N/A'}"+ if item.file:+ line += f" - {Path(item.file).name}"+ line += duration+ sys.stdout.write(line + "\n")++ if item.status == "completed":+ completed += 1+ elif item.status == "failed":+ failed += 1++ if item.start_time and item.end_time:+ total_time += (item.end_time - item.start_time)++ # Final stats+ sys.stdout.write("\n" + "=" * 80 + "\n")+ if self.use_emoji:+ sys.stdout.write(f"β Completed: {completed} | β Failed: {failed} | β±οΈ Total Time: {total_time:.2f}s\n")+ else:+ sys.stdout.write(f"Completed: {completed} | Failed: {failed} | Total Time: {total_time:.2f}s\n")+ sys.stdout.write("=" * 80 + "\n")+ sys.stdout.flush()++ def clear(self) -> None:+ """Clear console display."""+ with self.lock:+ sys.stdout.write("\r" + " " * 100 + "\r")+ sys.stdout.flush()+ self.current_lines.clear()+++class JupyterProgressDisplay(ProgressDisplay):+ """Jupyter notebook progress display."""++ def __init__(self, use_emoji: bool = True):+ self.use_emoji = use_emoji+ self.display_handle = None+ self.items: List[ProgressItem] = []++ def _get_emoji_for_module(self, module: str) -> str:+ """Get emoji for module type."""+ if not self.use_emoji:+ return ""++ emoji_map = {+ "ingest": "π₯",+ "parse": "π",+ "kg": "π§ ",+ "embeddings": "πΎ",+ "normalize": "π§",+ "ontology": "π",+ "semantic_extract": "π―",+ "seed": "π±",+ "split": "βοΈ",+ "triple_store": "ποΈ",+ "vector_store": "π",+ "export": "πΎ",+ "reasoning": "π€",+ "kg_qa": "β ",+ "visualization": "π",+ "context": "π",+ "conflicts": "β οΈ",+ "deduplication": "π",+ "pipeline": "βοΈ",+ }++ module_lower = module.lower()+ for key, emoji in emoji_map.items():+ if key in module_lower:+ return emoji+ return "β³"++ def _get_status_emoji(self, status: str) -> str:+ """Get emoji for status."""+ if not self.use_emoji:+ return ""++ status_map = {+ "pending": "β³",+ "running": "π",+ "completed": "β ",+ "failed": "β",+ }+ return status_map.get(status, "β³")++ def _get_action_message(self, module: Optional[str], message: str) -> str:+ """Get action message based on module."""+ # Extract action from message if it contains "Semantica:"+ if message and "Semantica:" in message:+ # Use the message as-is if it already has Semantica format+ return message.split("Semantica:")[-1].strip() if "Semantica:" in message else message++ # Map modules to actions+ action_map = {+ "ingest": "is ingesting",+ "parse": "is parsing",+ "kg": "is building",+ "embeddings": "is embedding",+ "normalize": "is normalizing",+ "ontology": "is generating",+ "semantic_extract": "is extracting",+ "seed": "is seeding",+ "split": "is splitting",+ "triple_store": "is storing",+ "vector_store": "is indexing",+ "export": "is exporting",+ "reasoning": "is reasoning",+ "kg_qa": "is validating",+ "visualization": "is visualizing",+ "context": "is processing",+ "conflicts": "is resolving",+ "deduplication": "is deduplicating",+ "pipeline": "is executing",+ "core": "is processing",+ }++ action = action_map.get(module or "", "is processing")+ return f"Semantica {action}"++ def _build_html(self, items: List[ProgressItem]) -> str:+ """Build HTML for display."""+ html_parts = ["<div style='font-family: monospace;'>"]++ # Current status+ html_parts.append("<h4>π§ Semantica - π Current Progress</h4>")+ html_parts.append("<table style='width: 100%; border-collapse: collapse;'>")+ html_parts.append("<tr><th>Status</th><th>Action</th><th>Module</th><th>Submodule</th><th>File</th><th>Time</th></tr>")++ # Show last 10 items+ for item in items[-10:]:+ status_emoji = self._get_status_emoji(item.status)+ module_emoji = self._get_emoji_for_module(item.module or "")+ action_msg = self._get_action_message(item.module, item.message)++ elapsed = ""+ if item.start_time:+ if item.end_time:+ elapsed = f"{(item.end_time - item.start_time):.2f}s"+ else:+ elapsed = f"{(time.time() - item.start_time):.2f}s"++ file_name = Path(item.file).name if item.file else "-"++ html_parts.append(+ f"<tr>"+ f"<td>{status_emoji}</td>"+ f"<td>{action_msg}</td>"+ f"<td>{module_emoji} {item.module or 'N/A'}</td>"+ f"<td>{item.submodule or 'N/A'}</td>"+ f"<td>{file_name}</td>"+ f"<td>{elapsed}</td>"+ f"</tr>"+ )++ html_parts.append("</table>")+ html_parts.append("</div>")++ return "".join(html_parts)++ def update(self, item: ProgressItem) -> None:+ """Update Jupyter progress display."""+ # Add or update item+ existing = None+ for i, existing_item in enumerate(self.items):+ if (existing_item.module == item.module and+ existing_item.submodule == item.submodule and+ existing_item.file == item.file):+ existing = i+ break++ if existing is not None:+ self.items[existing] = item+ else:+ self.items.append(item)++ # Update display+ if IPYTHON_AVAILABLE:+ html = self._build_html(self.items)+ if self.display_handle is None:+ self.display_handle = display(HTML(html), display_id=True)+ else:+ self.display_handle.update(HTML(html))++ def show_summary(self, items: List[ProgressItem]) -> None:+ """Show final summary in Jupyter."""+ if not IPYTHON_AVAILABLE:+ return++ html_parts = ["<div style='font-family: monospace;'>"]+ html_parts.append("<h3>π§ Semantica - π Progress Summary</h3>")++ # Group by module+ by_module: Dict[str, List[ProgressItem]] = {}+ for item in items:+ module = item.module or "unknown"+ if module not in by_module:+ by_module[module] = []+ by_module[module].append(item)++ # Summary table+ html_parts.append("<table style='width: 100%; border-collapse: collapse; border: 1px solid #ddd;'>")+ html_parts.append(+ "<tr style='background-color: #f2f2f2;'>"+ "<th>Module</th><th>Submodule</th><th>File</th><th>Status</th><th>Time</th>"+ "</tr>"+ )++ completed = 0+ failed = 0+ total_time = 0.0++ for module, module_items in by_module.items():+ module_emoji = self._get_emoji_for_module(module)+ for item in module_items:+ status_emoji = self._get_status_emoji(item.status)+ duration = ""+ if item.start_time and item.end_time:+ duration = f"{(item.end_time - item.start_time):.2f}s"+ total_time += (item.end_time - item.start_time)+ elif item.start_time:+ duration = "running..."++ file_name = Path(item.file).name if item.file else "-"++ html_parts.append(+ f"<tr>"+ f"<td>{module_emoji} {module}</td>"+ f"<td>{item.submodule or 'N/A'}</td>"+ f"<td>{file_name}</td>"+ f"<td>{status_emoji}</td>"+ f"<td>{duration}</td>"+ f"</tr>"+ )++ if item.status == "completed":+ completed += 1+ elif item.status == "failed":+ failed += 1++ html_parts.append("</table>")++ # Stats+ html_parts.append(f"<p><strong>β Completed:</strong> {completed} | <strong>β Failed:</strong> {failed} | <strong>β±οΈ Total Time:</strong> {total_time:.2f}s</p>")+ html_parts.append("</div>")++ html = "".join(html_parts)+ display(HTML(html))++ def clear(self) -> None:+ """Clear Jupyter display."""+ if IPYTHON_AVAILABLE and self.display_handle:+ clear_output(wait=True)+ self.display_handle = None+ self.items.clear()+++class FileProgressDisplay(ProgressDisplay):+ """File-based progress display (logs)."""++ def __init__(self, logger=None):+ self.logger = logger or get_logger("progress")+ self.items: List[ProgressItem] = []++ def update(self, item: ProgressItem) -> None:+ """Update file progress display."""+ # Add or update item+ existing = None+ for i, existing_item in enumerate(self.items):+ if (existing_item.module == item.module and+ existing_item.submodule == item.submodule and+ existing_item.file == item.file):+ existing = i+ break++ if existing is not None:+ self.items[existing] = item+ else:+ self.items.append(item)++ # Log progress+ parts = [f"[{item.status.upper()}]"]+ if item.module:+ parts.append(f"Module: {item.module}")+ if item.submodule:+ parts.append(f"Submodule: {item.submodule}")+ if item.file:+ parts.append(f"File: {Path(item.file).name}")+ if item.message:+ parts.append(f"Message: {item.message}")++ self.logger.info(" | ".join(parts))++ def show_summary(self, items: List[ProgressItem]) -> None:+ """Show final summary in log file."""+ self.logger.info("=" * 80)+ self.logger.info("SEMANTICA - PROGRESS SUMMARY")+ self.logger.info("=" * 80)++ # Group by module+ by_module: Dict[str, List[ProgressItem]] = {}+ for item in items:+ module = item.module or "unknown"+ if module not in by_module:+ by_module[module] = []+ by_module[module].append(item)++ completed = 0+ failed = 0+ total_time = 0.0++ for module, module_items in by_module.items():+ self.logger.info(f"\n{module.upper()}:")+ for item in module_items:+ duration = ""+ if item.start_time and item.end_time:+ duration = f" ({(item.end_time - item.start_time):.2f}s)"+ total_time += (item.end_time - item.start_time)++ file_name = Path(item.file).name if item.file else "N/A"+ self.logger.info(+ f" [{item.status.upper()}] {item.submodule or 'N/A'} - {file_name}{duration}"+ )++ if item.status == "completed":+ completed += 1+ elif item.status == "failed":+ failed += 1++ self.logger.info("=" * 80)+ self.logger.info(f"Completed: {completed} | Failed: {failed} | Total Time: {total_time:.2f}s")+ self.logger.info("=" * 80)++ def clear(self) -> None:+ """Clear file display (no-op for logs)."""+ pass+++class ModuleDetector:+ """Utility for automatic module/submodule detection."""++ @staticmethod+ def detect_from_frame(frame) -> Tuple[Optional[str], Optional[str]]:+ """+ Detect module and submodule from frame.++ Returns:+ Tuple of (module_name, submodule_name)+ """+ try:+ # Get the frame's module+ module_name = frame.f_globals.get('__name__', '')++ # Extract module name (e.g., 'semantica.ingest.file_ingestor' -> 'ingest')+ if 'semantica.' in module_name:+ parts = module_name.split('.')+ if len(parts) >= 2:+ module_name = parts[1] # Get 'ingest', 'parse', etc.+ else:+ module_name = None+ else:+ module_name = None++ # Get class name from 'self' if available+ submodule_name = None+ if 'self' in frame.f_locals:+ self_obj = frame.f_locals['self']+ if hasattr(self_obj, '__class__'):+ submodule_name = self_obj.__class__.__name__+ elif 'cls' in frame.f_locals:+ cls_obj = frame.f_locals['cls']+ if isinstance(cls_obj, type):+ submodule_name = cls_obj.__name__++ # Fallback: try to get from frame code+ if not submodule_name:+ code = frame.f_code+ # Try to extract class name from qualified name+ if hasattr(code, 'co_qualname'):+ qualname = code.co_qualname+ if '.' in qualname:+ submodule_name = qualname.split('.')[0]++ return module_name, submodule_name++ except Exception:+ return None, None++ @staticmethod+ def detect_from_call_stack(depth: int = 2) -> Tuple[Optional[str], Optional[str]]:+ """+ Detect module and submodule from call stack.++ Args:+ depth: Stack depth to check (default: 2, meaning caller's caller)++ Returns:+ Tuple of (module_name, submodule_name)+ """+ try:+ frame = inspect.currentframe()+ if frame is None:+ return None, None++ # Go up the stack to find the actual caller+ for _ in range(depth):+ frame = frame.f_back+ if frame is None:+ return None, None++ return ModuleDetector.detect_from_frame(frame)+ except Exception:+ return None, None+++class ProgressTracker:+ """Main progress tracking coordinator."""++ _instance: Optional['ProgressTracker'] = None+ _lock = threading.Lock()++ def __init__(self, enabled: bool = True, use_emoji: bool = True,+ update_interval: float = 0.1):+ """+ Initialize progress tracker.++ Args:+ enabled: Enable progress tracking+ use_emoji: Use emoji indicators+ update_interval: Minimum time between updates (seconds)+ """+ self.enabled = enabled+ self.use_emoji = use_emoji+ self.update_interval = update_interval++ # Detect environment+ self.is_jupyter = self._detect_jupyter()++ # Create displays+ self.displays: List[ProgressDisplay] = []++ if self.is_jupyter and IPYTHON_AVAILABLE:+ self.displays.append(JupyterProgressDisplay(use_emoji=use_emoji))+ else:+ self.displays.append(ConsoleProgressDisplay(use_emoji=use_emoji,+ update_interval=update_interval))++ # Always add file display+ self.displays.append(FileProgressDisplay())++ # Track items+ self.items: List[ProgressItem] = []+ self.active_items: Dict[str, ProgressItem] = {}+ self.lock = threading.Lock()++ def _detect_jupyter(self) -> bool:+ """Detect if running in Jupyter notebook."""+ if not IPYTHON_AVAILABLE:+ return False+ try:+ ipython = get_ipython()+ return ipython is not None and hasattr(ipython, 'kernel')+ except Exception:+ return False++ @classmethod+ def get_instance(cls) -> 'ProgressTracker':+ """Get singleton instance."""+ if cls._instance is None:+ with cls._lock:+ if cls._instance is None:+ cls._instance = cls()+ return cls._instance++ def start_tracking(self, file: Optional[str] = None,+ module: Optional[str] = None,+ submodule: Optional[str] = None,+ message: str = "") -> str:+ """+ Start tracking a progress item.++ Args:+ file: File being processed+ module: Module name+ submodule: Submodule/class name+ message: Progress message++ Returns:+ Tracking ID+ """+ if not self.enabled:+ return ""++ # Auto-detect if not provided+ if not module or not submodule:+ detected_module, detected_submodule = ModuleDetector.detect_from_call_stack(depth=3)+ module = module or detected_module+ submodule = submodule or detected_submodule++ # Create tracking ID+ tracking_id = f"{module}:{submodule}:{file or ''}"++ with self.lock:+ item = ProgressItem(+ file=file,+ module=module,+ submodule=submodule,+ status="running",+ start_time=time.time(),+ message=message,+ emoji=self._get_emoji_for_module(module or "")+ )++ self.active_items[tracking_id] = item++ # Update displays+ for display in self.displays:+ display.update(item)++ return tracking_id++ def update_tracking(self, tracking_id: str, status: str = "running",+ message: str = "") -> None:+ """+ Update tracking status.++ Args:+ tracking_id: Tracking ID from start_tracking+ status: New status (running, completed, failed)+ message: Progress message+ """+ if not self.enabled or not tracking_id:+ return++ with self.lock:+ if tracking_id in self.active_items:+ item = self.active_items[tracking_id]+ item.status = status+ item.message = message++ if status in ("completed", "failed"):+ item.end_time = time.time()+ # Move to completed items+ self.items.append(item)+ del self.active_items[tracking_id]++ # Update displays+ for display in self.displays:+ display.update(item)++ def stop_tracking(self, tracking_id: str, status: str = "completed",+ message: str = "") -> None:+ """+ Stop tracking an item.++ Args:+ tracking_id: Tracking ID from start_tracking+ status: Final status (completed, failed)+ message: Final message+ """+ self.update_tracking(tracking_id, status=status, message=message)++ def _get_emoji_for_module(self, module: str) -> str:+ """Get emoji for module."""+ if not self.use_emoji or not module:+ return ""++ emoji_map = {+ "ingest": "π₯",+ "parse": "π",+ "kg": "π§ ",+ "embeddings": "πΎ",+ "normalize": "π§",+ "ontology": "π",+ "semantic_extract": "π―",+ "seed": "π±",+ "split": "βοΈ",+ "triple_store": "ποΈ",+ "vector_store": "π",+ "export": "πΎ",+ "reasoning": "π€",+ "kg_qa": "β ",+ "visualization": "π",+ "context": "π",+ "conflicts": "β οΈ",+ "deduplication": "π",+ "pipeline": "βοΈ",+ }++ module_lower = module.lower()+ for key, emoji in emoji_map.items():+ if key in module_lower:+ return emoji+ return "β³"++ def show_summary(self) -> None:+ """Show final progress summary."""+ if not self.enabled:+ return++ with self.lock:+ # Add any remaining active items+ all_items = self.items + list(self.active_items.values())++ # Show summary on all displays+ for display in self.displays:+ display.show_summary(all_items)++ @contextmanager+ def track(self, file: Optional[str] = None,+ module: Optional[str] = None,+ submodule: Optional[str] = None,+ message: str = ""):+ """+ Context manager for automatic tracking.++ Usage:+ with progress_tracker.track(file="doc.pdf", message="Processing"):+ # code here+ """+ tracking_id = self.start_tracking(file=file, module=module,+ submodule=submodule, message=message)+ try:+ yield tracking_id+ self.stop_tracking(tracking_id, status="completed")+ except Exception as e:+ self.stop_tracking(tracking_id, status="failed", message=str(e))+ raise+++# Global singleton instance+_global_tracker: Optional[ProgressTracker] = None+++def get_progress_tracker() -> ProgressTracker:+ """Get global progress tracker instance."""+ global _global_tracker+ if _global_tracker is None:+ _global_tracker = ProgressTracker.get_instance()+ return _global_tracker+++def track_progress(file: Optional[str] = None,+ module: Optional[str] = None,+ submodule: Optional[str] = None):+ """+ Decorator for automatic progress tracking.++ Usage:+ @track_progress+ def my_function():+ # Automatically tracked+ pass++ @track_progress(file="doc.pdf")+ def process_file():+ # Tracked with file context+ pass+ """+ def decorator(func: Callable) -> Callable:+ def wrapper(*args, **kwargs):+ tracker = get_progress_tracker()++ # Try to extract file from args/kwargs+ detected_file = file+ if not detected_file:+ # Look for common file parameter names+ for arg_name in ['file', 'file_path', 'path', 'source', 'filename']:+ if arg_name in kwargs:+ detected_file = str(kwargs[arg_name])+ break+ elif args and isinstance(args[0], (str, Path)):+ detected_file = str(args[0])+ break++ # Auto-detect module/submodule if not provided+ detected_module = module+ detected_submodule = submodule+ if not detected_module or not detected_submodule:+ frame_module, frame_submodule = ModuleDetector.detect_from_call_stack(depth=2)+ detected_module = detected_module or frame_module+ detected_submodule = detected_submodule or frame_submodule++ # Use function name as fallback for submodule+ if not detected_submodule:+ detected_submodule = func.__name__++ # Start tracking+ tracking_id = tracker.start_tracking(+ file=detected_file,+ module=detected_module,+ submodule=detected_submodule,+ message=f"Running {func.__name__}"+ )++ try:+ result = func(*args, **kwargs)+ tracker.stop_tracking(tracking_id, status="completed",+ message=f"Completed {func.__name__}")+ return result+ except Exception as e:+ tracker.stop_tracking(tracking_id, status="failed",+ message=f"Failed {func.__name__}: {str(e)}")+ raise++ wrapper.__name__ = func.__name__+ wrapper.__doc__ = func.__doc__+ return wrapper++ # Handle both @track_progress and @track_progress(...) usage+ if callable(file):+ # Used as @track_progress without parentheses+ func = file+ file = None+ return decorator(func)+ else:+ # Used as @track_progress(...) with arguments+ return decorator+