Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

refactor(ingest): enhance documentation and code quality for all ingest modules

KaifAhmad15d864b0605f2
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.py
index f319e5bb..0298f382 100644
--- a/semantica/ingest/__init__.py
+++ b/semantica/ingest/__init__.py
@@ -11,8 +11,12 @@ Exports:
- RepoIngestor: Git repository processing
- EmailIngestor: Email protocol handling
- DBIngestor: Database export handling
+ - build: Module-level build function for data ingestion
"""
+from typing import Any, Dict, List, Optional, Union
+from pathlib import Path
+
from .file_ingestor import FileIngestor, FileObject, FileTypeDetector, CloudStorageIngestor
from .web_ingestor import WebIngestor, WebContent, RateLimiter, RobotsChecker, ContentExtractor, SitemapCrawler
from .feed_ingestor import FeedIngestor, FeedItem, FeedData, FeedParser, FeedMonitor
@@ -74,4 +78,112 @@ __all__ = [
"TableData",
"DatabaseConnector",
"DataExporter",
+ "build",
]
+
+
+def build(
+ sources: Union[List[Union[str, Path]], str, Path],
+ source_type: str = "file",
+ recursive: bool = True,
+ read_content: bool = True,
+ **options
+) -> Dict[str, Any]:
+ """
+ Ingest data from sources (module-level convenience function).
+
+ This is a user-friendly wrapper that automatically selects the appropriate
+ ingestor based on source type and ingests the data.
+
+ Args:
+ sources: Data source(s) - can be file paths, URLs, directories, etc.
+ source_type: Type of source - "file", "web", "feed", "stream", "repo", "email", "db" (default: "file")
+ recursive: For directories, whether to ingest recursively (default: True)
+ read_content: Whether to read file content (default: True)
+ **options: Additional ingestion options
+
+ Returns:
+ Dictionary containing:
+ - files: List of ingested file objects (for file ingestion)
+ - content: Ingested content (for web/feed ingestion)
+ - metadata: Ingestion metadata
+ - statistics: Ingestion statistics
+
+ Examples:
+ >>> import semantica
+ >>> result = semantica.ingest.build(
+ ... sources=["doc1.pdf", "doc2.docx"],
+ ... source_type="file",
+ ... read_content=True
+ ... )
+ >>> print(f"Ingested {len(result['files'])} files")
+ """
+ # Normalize sources to list
+ if isinstance(sources, (str, Path)):
+ sources = [sources]
+
+ results = {
+ "files": [],
+ "content": [],
+ "metadata": {},
+ "statistics": {}
+ }
+
+ if source_type == "file":
+ # Use FileIngestor
+ ingestor = FileIngestor(config=options.get("config", {}), **options)
+
+ file_objects = []
+ for source in sources:
+ source_path = Path(source)
+ if source_path.is_dir():
+ # Ingest directory
+ files = ingestor.ingest_directory(source_path, recursive=recursive, **options)
+ file_objects.extend(files)
+ elif source_path.is_file():
+ # Ingest single file
+ file_obj = ingestor.ingest_file(source_path, read_content=read_content, **options)
+ file_objects.append(file_obj)
+ else:
+ # Try as file path string
+ try:
+ file_obj = ingestor.ingest_file(source, read_content=read_content, **options)
+ file_objects.append(file_obj)
+ except Exception as e:
+ results["statistics"].setdefault("errors", []).append({
+ "source": str(source),
+ "error": str(e)
+ })
+
+ results["files"] = file_objects
+ results["statistics"] = {
+ "total_sources": len(sources),
+ "ingested_files": len(file_objects),
+ "errors": len(results["statistics"].get("errors", []))
+ }
+
+ elif source_type == "web":
+ # Use WebIngestor
+ from .web_ingestor import WebIngestor
+ ingestor = WebIngestor(config=options.get("config", {}), **options)
+
+ web_contents = []
+ for source in sources:
+ if isinstance(source, str) and (source.startswith("http://") or source.startswith("https://")):
+ content = ingestor.ingest_url(source, **options)
+ web_contents.append(content)
+
+ results["content"] = web_contents
+ results["statistics"] = {
+ "total_urls": len(sources),
+ "ingested_pages": len(web_contents)
+ }
+
+ else:
+ # For other types, return placeholder
+ results["statistics"] = {
+ "message": f"Source type '{source_type}' ingestion not yet implemented in build() function",
+ "suggestion": f"Use {source_type.capitalize()}Ingestor class directly"
+ }
+
+ return results
diff --git a/semantica/ingest/db_ingestor.py b/semantica/ingest/db_ingestor.py
index 9e9db43e..9a12097e 100644
--- a/semantica/ingest/db_ingestor.py
+++ b/semantica/ingest/db_ingestor.py
@@ -1,19 +1,31 @@
"""
Database Ingestion Module
-Handles database export and data extraction.
+This module provides comprehensive database ingestion capabilities for the
+Semantica framework, enabling data extraction from various database systems.
Key Features:
- - Database connection management
- - SQL query execution
+ - Multiple database support (PostgreSQL, MySQL, SQLite, Oracle, SQL Server)
+ - Database connection management with connection pooling
+ - SQL query execution and result processing
- Data export and transformation
- - Schema analysis
- - Data type handling
+ - Schema analysis and introspection
+ - Data type handling and conversion
+ - Large dataset processing with pagination
Main Classes:
- DBIngestor: Main database ingestion class
- DatabaseConnector: Database connection handler
- DataExporter: Data export processor
+
+Example Usage:
+ >>> from semantica.ingest import DBIngestor
+ >>> ingestor = DBIngestor()
+ >>> data = ingestor.ingest_database("postgresql://user:pass@localhost/db")
+ >>> table_data = ingestor.export_table("postgresql://...", "users", limit=100)
+
+Author: Semantica Contributors
+License: MIT
"""
import json
@@ -46,9 +58,21 @@ class DatabaseConnector:
"""
Database connection management.
- Manages connections to various databases,
- handles connection pooling and reuse,
- and provides unified interface for different DBs.
+ This class manages connections to various database systems, handles
+ connection pooling and reuse, and provides a unified interface for
+ different database types.
+
+ Supported Databases:
+ - PostgreSQL (postgresql, postgres)
+ - MySQL/MariaDB (mysql, mariadb)
+ - SQLite (sqlite)
+ - Oracle (oracle)
+ - SQL Server (mssql, sqlserver)
+
+ Example Usage:
+ >>> connector = DatabaseConnector("postgresql")
+ >>> engine = connector.connect("postgresql://user:pass@localhost/db")
+ >>> connector.disconnect()
"""
SUPPORTED_DATABASES = {
@@ -62,28 +86,44 @@ class DatabaseConnector:
'sqlserver': 'mssql+pyodbc',
}
- def __init__(self, db_type: str, **config):
+ def __init__(self, db_type: str = "", **config):
"""
Initialize database connector.
+ Sets up the connector with database type and configuration. Database
+ type can be auto-detected from connection string if not provided.
+
Args:
- db_type: Database type (postgresql, mysql, sqlite, etc.)
- **config: Connection configuration
+ db_type: Database type (postgresql, mysql, sqlite, etc.) (optional)
+ **config: Connection configuration options
"""
self.logger = get_logger("database_connector")
- self.db_type = db_type.lower()
+ self.db_type = db_type.lower() if db_type else ""
self.config = config
self.engine: Optional[Engine] = None
+
+ self.logger.debug(f"Database connector initialized: db_type={db_type or 'auto-detect'}")
def connect(self, connection_string: str) -> Engine:
"""
Establish database connection.
+ This method creates a SQLAlchemy engine for the database connection
+ string, auto-detects database type if not specified, and tests the
+ connection to ensure it's working.
+
Args:
- connection_string: Database connection string
+ connection_string: Database connection string (SQLAlchemy format)
+ Examples:
+ - "postgresql://user:pass@localhost/db"
+ - "mysql+pymysql://user:pass@localhost/db"
+ - "sqlite:///path/to/db.sqlite"
Returns:
- Engine: SQLAlchemy engine object
+ Engine: SQLAlchemy engine object for database operations
+
+ Raises:
+ ProcessingError: If connection fails or database type is unsupported
"""
try:
# Parse connection string to detect database type
@@ -91,29 +131,39 @@ class DatabaseConnector:
# Determine database type from connection string if not provided
if parsed.scheme:
- db_type = parsed.scheme.split('+')[0]
+ db_type = parsed.scheme.split('+')[0] # Remove driver prefix (e.g., mysql+pymysql -> mysql)
if db_type in self.SUPPORTED_DATABASES:
self.db_type = db_type
+ self.logger.debug(f"Auto-detected database type: {db_type}")
- # Get SQLAlchemy dialect
- dialect = self.SUPPORTED_DATABASES.get(self.db_type, self.db_type)
+ # Validate database type
+ if self.db_type and self.db_type not in self.SUPPORTED_DATABASES:
+ raise ValidationError(
+ f"Unsupported database type: {self.db_type}. "
+ f"Supported types: {list(self.SUPPORTED_DATABASES.keys())}"
+ )
- # Create engine
+ # Create SQLAlchemy engine
self.engine = create_engine(connection_string, echo=False)
- # Test connection
+ # Test connection with a simple query
with self.engine.connect() as conn:
conn.execute(text("SELECT 1"))
- self.logger.info(f"Connected to {self.db_type} database")
+ self.logger.info(f"Connected to {self.db_type or 'database'}")
return self.engine
except Exception as e:
self.logger.error(f"Failed to connect to database: {e}")
- raise ProcessingError(f"Failed to connect to database: {e}")
+ raise ProcessingError(f"Failed to connect to database: {e}") from e
def disconnect(self):
- """Close database connection."""
+ """
+ Close database connection.
+
+ This method disposes of the SQLAlchemy engine and closes all connections
+ in the connection pool. Should be called when done with database operations.
+ """
if self.engine:
self.engine.dispose()
self.engine = None
@@ -121,13 +171,16 @@ class DatabaseConnector:
def test_connection(self, connection_string: str) -> bool:
"""
- Test database connection.
+ Test database connection without creating a persistent connection.
+
+ This method creates a temporary connection, tests it with a simple query,
+ and immediately closes it. Useful for connection validation.
Args:
- connection_string: Database connection string
+ connection_string: Database connection string to test
Returns:
- bool: True if connection successful
+ bool: True if connection successful, False otherwise
"""
try:
engine = create_engine(connection_string)
@@ -135,7 +188,8 @@ class DatabaseConnector:
conn.execute(text("SELECT 1"))
engine.dispose()
return True
- except Exception:
+ except Exception as e:
+ self.logger.debug(f"Connection test failed: {e}")
return False
@@ -143,18 +197,24 @@ class DataExporter:
"""
Database data export and transformation.
- Exports data from database tables,
- transforms data to standard formats,
- handles different data types,
- and manages large dataset exports.
+ This class exports data from database tables, transforms data to standard
+ formats, handles different data types, and manages large dataset exports
+ with pagination support.
+
+ Example Usage:
+ >>> exporter = DataExporter()
+ >>> table_data = exporter.export_table_data(engine, "users", limit=100)
+ >>> schema = exporter.export_schema(engine)
"""
def __init__(self, **config):
"""
Initialize data exporter.
+ Sets up the exporter with configuration options.
+
Args:
- **config: Exporter configuration
+ **config: Exporter configuration options (currently unused)
"""
self.logger = get_logger("data_exporter")
self.config = config
@@ -164,23 +224,39 @@ class DataExporter:
connection: Engine,
table_name: str,
schema: Optional[str] = None,
+ limit: Optional[int] = None,
+ offset: Optional[int] = None,
+ where: Optional[str] = None,
+ order_by: Optional[str] = None,
**options
) -> TableData:
"""
Export data from database table.
+ This method exports data from a database table with optional filtering,
+ pagination, and ordering. Converts database types to JSON-serializable
+ formats (e.g., datetime to ISO format strings).
+
Args:
- connection: Database connection engine
- table_name: Table name to export
- schema: Schema name (optional)
- **options: Export options:
- - limit: Maximum number of rows
- - offset: Row offset
- - where: WHERE clause
- - order_by: ORDER BY clause
+ connection: SQLAlchemy database connection engine
+ table_name: Name of the table to export
+ schema: Schema name (for databases with schema support, optional)
+ limit: Maximum number of rows to export (optional)
+ offset: Row offset for pagination (optional)
+ where: WHERE clause for filtering (optional, e.g., "age > 18")
+ order_by: ORDER BY clause for sorting (optional, e.g., "name ASC")
+ **options: Additional export options (unused)
Returns:
- TableData: Exported table data
+ TableData: Exported table data object containing:
+ - table_name: Table name
+ - columns: List of column information dictionaries
+ - rows: List of row dictionaries
+ - row_count: Total number of rows (or exported count if limit applied)
+ - schema: Schema name (if provided)
+
+ Raises:
+ ProcessingError: If table export fails
"""
try:
inspector = inspect(connection)
@@ -197,22 +273,28 @@ class DataExporter:
for col in columns
]
- # Build query
- query = f'SELECT * FROM {f"{schema}." if schema else ""}"{table_name}"'
+ self.logger.debug(
+ f"Exporting table {table_name}: {len(column_info)} column(s), "
+ f"schema={schema}, limit={limit}"
+ )
+
+ # Build SQL query with optional clauses
+ table_ref = f'{f"{schema}." if schema else ""}"{table_name}"'
+ query = f'SELECT * FROM {table_ref}'
- if options.get("where"):
- query += f" WHERE {options['where']}"
+ if where:
+ query += f" WHERE {where}"
- if options.get("order_by"):
- query += f" ORDER BY {options['order_by']}"
+ if order_by:
+ query += f" ORDER BY {order_by}"
- if options.get("limit"):
- query += f" LIMIT {options['limit']}"
+ if limit:
+ query += f" LIMIT {limit}"
- if options.get("offset"):
- query += f" OFFSET {options['offset']}"
+ if offset:
+ query += f" OFFSET {offset}"
- # Execute query
+ # Execute query and process results
with connection.connect() as conn:
result = conn.execute(text(query))
rows = []
@@ -223,20 +305,26 @@ class DataExporter:
if isinstance(value, datetime):
row_dict[col_name] = value.isoformat()
elif hasattr(value, '__dict__'):
+ # Complex types - convert to string
row_dict[col_name] = str(value)
else:
row_dict[col_name] = value
rows.append(row_dict)
- # Get row count if limit not applied
+ # Get total row count if limit not applied
row_count = len(rows)
- if not options.get("limit"):
- count_query = f'SELECT COUNT(*) FROM {f"{schema}." if schema else ""}"{table_name}"'
- if options.get("where"):
- count_query += f" WHERE {options['where']}"
+ if not limit:
+ count_query = f'SELECT COUNT(*) FROM {table_ref}'
+ if where:
+ count_query += f" WHERE {where}"
count_result = conn.execute(text(count_query))
row_count = count_result.scalar()
+ self.logger.debug(
+ f"Exported {len(rows)} row(s) from table {table_name} "
+ f"(total: {row_count})"
+ )
+
return TableData(
table_name=table_name,
columns=column_info,
@@ -247,18 +335,27 @@ class DataExporter:
except Exception as e:
self.logger.error(f"Failed to export table {table_name}: {e}")
- raise ProcessingError(f"Failed to export table: {e}")
+ raise ProcessingError(f"Failed to export table: {e}") from e
- def transform_data(self, raw_data: List[Dict[str, Any]], schema_info: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def transform_data(
+ self,
+ raw_data: List[Dict[str, Any]],
+ schema_info: Dict[str, Any]
+ ) -> List[Dict[str, Any]]:
"""
Transform raw database data.
+ This method applies transformations to raw database rows, including
+ string cleaning and normalization. Can be extended with custom
+ transformation logic.
+
Args:
- raw_data: Raw database rows
- schema_info: Schema information
+ raw_data: List of raw database row dictionaries
+ schema_info: Schema information dictionary (currently unused,
+ reserved for schema-aware transformations)
Returns:
- list: Transformed data
+ list: List of transformed row dictionaries
"""
transformed = []
@@ -269,8 +366,8 @@ class DataExporter:
if value is None:
transformed_row[col_name] = None
elif isinstance(value, str):
- # Clean and normalize strings
- transformed_row[col_name] = value.strip() if isinstance(value, str) else value
+ # Clean and normalize strings (strip whitespace)
+ transformed_row[col_name] = value.strip()
else:
transformed_row[col_name] = value
@@ -278,16 +375,34 @@ class DataExporter:
return transformed
- def export_schema(self, connection: Engine, schema: Optional[str] = None) -> Dict[str, Any]:
+ def export_schema(
+ self,
+ connection: Engine,
+ schema: Optional[str] = None
+ ) -> Dict[str, Any]:
"""
Export database schema information.
+ This method introspects the database schema and exports comprehensive
+ information about tables, columns, primary keys, indexes, foreign keys,
+ and views.
+
Args:
- connection: Database connection engine
- schema: Schema name (optional)
+ connection: SQLAlchemy database connection engine
+ schema: Schema name (for databases with schema support, optional)
Returns:
- dict: Schema information
+ dict: Schema information dictionary containing:
+ - tables: List of table information dictionaries with:
+ - name: Table name
+ - columns: List of column information
+ - primary_keys: List of primary key column names
+ - indexes: List of index names
+ - views: List of view names
+ - foreign_keys: List of foreign key constraint dictionaries
+
+ Raises:
+ ProcessingError: If schema export fails
"""
try:
inspector = inspect(connection)
@@ -298,8 +413,10 @@ class DataExporter:
"foreign_keys": []
}
- # Get tables
+ # Get all tables in schema
tables = inspector.get_table_names(schema=schema)
+ self.logger.debug(f"Found {len(tables)} table(s) in schema: {schema or 'default'}")
+
for table_name in tables:
table_info = {
"name": table_name,
@@ -308,7 +425,7 @@ class DataExporter:
"indexes": []
}
- # Get columns
+ # Get column information
columns = inspector.get_columns(table_name, schema=schema)
for col in columns:
table_info["columns"].append({
@@ -318,25 +435,33 @@ class DataExporter:
"primary_key": col.get("primary_key", False)
})
- # Get primary keys
- pk = inspector.get_pk_constraint(table_name, schema=schema)
- if pk:
- table_info["primary_keys"] = pk.get("constrained_columns", [])
+ # Get primary key constraints
+ try:
+ pk = inspector.get_pk_constraint(table_name, schema=schema)
+ if pk:
+ table_info["primary_keys"] = pk.get("constrained_columns", [])
+ except Exception:
+ pass
# Get indexes
- indexes = inspector.get_indexes(table_name, schema=schema)
- table_info["indexes"] = [idx["name"] for idx in indexes]
+ try:
+ indexes = inspector.get_indexes(table_name, schema=schema)
+ table_info["indexes"] = [idx["name"] for idx in indexes]
+ except Exception:
+ pass
schema_info["tables"].append(table_info)
- # Get views
+ # Get views (if supported)
try:
views = inspector.get_view_names(schema=schema)
schema_info["views"] = views
+ self.logger.debug(f"Found {len(views)} view(s) in schema")
except Exception:
+ # Views may not be supported by all databases
pass
- # Get foreign keys
+ # Get foreign key constraints
for table_name in tables:
try:
foreign_keys = inspector.get_foreign_keys(table_name, schema=schema)
@@ -344,111 +469,152 @@ class DataExporter:
except Exception:
pass
+ self.logger.debug(
+ f"Exported schema: {len(schema_info['tables'])} table(s), "
+ f"{len(schema_info['views'])} view(s), "
+ f"{len(schema_info['foreign_keys'])} foreign key(s)"
+ )
+
return schema_info
except Exception as e:
self.logger.error(f"Failed to export schema: {e}")
- raise ProcessingError(f"Failed to export schema: {e}")
+ raise ProcessingError(f"Failed to export schema: {e}") from e
class DBIngestor:
"""
Database ingestion handler.
- Connects to various database systems,
- executes SQL queries and exports data,
- handles different database schemas,
- and processes large datasets efficiently.
+ This class provides comprehensive database ingestion capabilities, connecting
+ to various database systems, executing SQL queries, exporting data, and
+ analyzing database schemas.
+
+ Features:
+ - Multiple database support (PostgreSQL, MySQL, SQLite, Oracle, SQL Server)
+ - Database connection management
+ - SQL query execution
+ - Table and schema export
+ - Data transformation
+ - Large dataset handling with pagination
- Attributes:
- connectors: Dictionary of database connectors
- exporter: Data export processor
- schema_analyzer: Database schema analyzer
- supported_databases: List of supported database types
-
- Methods:
- ingest_database(): Ingest entire database
- execute_query(): Execute SQL query
- export_table(): Export specific table
- analyze_schema(): Analyze database schema
+ Example Usage:
+ >>> ingestor = DBIngestor()
+ >>> data = ingestor.ingest_database("postgresql://user:pass@localhost/db")
+ >>> table_data = ingestor.export_table("postgresql://...", "users", limit=100)
+ >>> schema = ingestor.analyze_schema("postgresql://...")
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize database ingestor.
+ Sets up the ingestor with data exporter and configuration.
+
Args:
- config: Database ingestion configuration
- **kwargs: Additional configuration parameters
+ config: Optional database ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
"""
self.logger = get_logger("db_ingestor")
self.config = config or {}
self.config.update(kwargs)
- # Initialize connectors dictionary
+ # Initialize connectors dictionary (for connection reuse)
self.connectors: Dict[str, DatabaseConnector] = {}
- # Initialize exporter
+ # Initialize data exporter
self.exporter = DataExporter(**self.config)
# Supported databases
self.supported_databases = list(DatabaseConnector.SUPPORTED_DATABASES.keys())
+
+ self.logger.debug(
+ f"DB ingestor initialized with support for: {', '.join(self.supported_databases)}"
+ )
- def ingest_database(self, connection_string: str, **options) -> Dict[str, Any]:
+ def ingest_database(
+ self,
+ connection_string: str,
+ include_tables: Optional[List[str]] = None,
+ exclude_tables: Optional[List[str]] = None,
+ max_rows_per_table: Optional[int] = None,
+ **options
+ ) -> Dict[str, Any]:
"""
Ingest data from entire database.
+ This method connects to a database, analyzes the schema, and exports
+ data from all tables (or a filtered subset). Useful for full database
+ ingestion and backup scenarios.
+
Args:
connection_string: Database connection string
- **options: Processing options:
- - include_tables: List of specific tables to include
- - exclude_tables: List of tables to exclude
- - max_rows_per_table: Maximum rows per table
+ include_tables: List of specific table names to include (optional,
+ if provided, only these tables are exported)
+ exclude_tables: List of table names to exclude (optional,
+ default: empty list)
+ max_rows_per_table: Maximum number of rows to export per table
+ (optional, for large tables)
+ **options: Additional processing options (unused)
Returns:
- dict: Database content collection
+ dict: Database content dictionary containing:
+ - schema: Database schema information
+ - tables: Dictionary mapping table names to table data
+ - total_tables: Total number of tables exported
+ - connection_string: Connection string used
"""
# Connect to database
connector = DatabaseConnector("", **self.config)
engine = connector.connect(connection_string)
try:
- # Analyze schema
+ # Analyze schema first
schema = self.analyze_schema(connection_string)
- # Get table names
+ # Get all table names
inspector = inspect(engine)
all_tables = inspector.get_table_names()
- # Apply filters
- include_tables = options.get("include_tables")
- exclude_tables = options.get("exclude_tables", [])
+ 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 = {}
- max_rows = options.get("max_rows_per_table")
for table_name in tables:
try:
- table_options = {"limit": max_rows} if max_rows else {}
+ # Export table with optional row limit
table_info = self.exporter.export_table_data(
engine,
table_name,
- **table_options
+ limit=max_rows_per_table
)
table_data[table_name] = {
"columns": table_info.columns,
"row_count": table_info.row_count,
- "rows": table_info.rows[:max_rows] if max_rows else table_info.rows
+ "rows": table_info.rows
}
- self.logger.debug(f"Exported table {table_name}: {table_info.row_count} 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,
@@ -460,24 +626,43 @@ class DBIngestor:
finally:
connector.disconnect()
- def execute_query(self, connection_string: str, query: str, **params) -> List[Dict[str, Any]]:
+ def execute_query(
+ self,
+ connection_string: str,
+ query: str,
+ **params
+ ) -> List[Dict[str, Any]]:
"""
Execute SQL query and return results.
+ This method executes a SQL query with optional parameters and returns
+ results as a list of dictionaries. Converts database types to
+ JSON-serializable formats.
+
Args:
connection_string: Database connection string
- query: SQL query to execute
- **params: Query parameters
+ query: SQL query to execute (can include parameter placeholders)
+ **params: Query parameters (for parameterized queries)
Returns:
- list: Query results
+ list: List of row dictionaries, each representing a query result row
+
+ Raises:
+ ProcessingError: If query execution fails
+
+ Example:
+ >>> results = ingestor.execute_query(
+ ... "postgresql://...",
+ ... "SELECT * FROM users WHERE age > :min_age",
+ ... min_age=18
+ ... )
"""
connector = DatabaseConnector("", **self.config)
engine = connector.connect(connection_string)
try:
with engine.connect() as conn:
- # Execute query with parameters
+ # Execute query with parameters (parameterized queries for safety)
result = conn.execute(text(query), params)
# Convert results to list of dictionaries
@@ -485,19 +670,22 @@ class DBIngestor:
for row in result:
row_dict = {}
for col_name, value in row._mapping.items():
+ # Convert datetime to ISO format
if isinstance(value, datetime):
row_dict[col_name] = value.isoformat()
elif hasattr(value, '__dict__'):
+ # Complex types - convert to string
row_dict[col_name] = str(value)
else:
row_dict[col_name] = value
rows.append(row_dict)
+ self.logger.debug(f"Query executed: {len(rows)} row(s) returned")
return rows
except Exception as e:
self.logger.error(f"Failed to execute query: {e}")
- raise ProcessingError(f"Failed to execute query: {e}")
+ raise ProcessingError(f"Failed to execute query: {e}") from e
finally:
connector.disconnect()
@@ -506,72 +694,111 @@ class DBIngestor:
connection_string: str,
table_name: str,
schema: Optional[str] = None,
+ limit: Optional[int] = None,
+ offset: Optional[int] = None,
+ where: Optional[str] = None,
+ order_by: Optional[str] = None,
+ transform: bool = False,
**filters
) -> TableData:
"""
Export data from specific table.
+ This method exports data from a single database table with optional
+ filtering, pagination, ordering, and transformation.
+
Args:
connection_string: Database connection string
- table_name: Table name to export
- schema: Schema name (optional)
- **filters: Filtering criteria:
- - where: WHERE clause
- - limit: Maximum number of rows
- - offset: Row offset
- - order_by: ORDER BY clause
+ table_name: Name of the table to export
+ schema: Schema name (for databases with schema support, optional)
+ limit: Maximum number of rows to export (optional)
+ offset: Row offset for pagination (optional)
+ where: WHERE clause for filtering (optional, e.g., "status = 'active'")
+ order_by: ORDER BY clause for sorting (optional, e.g., "created_at DESC")
+ transform: Whether to apply data transformations (default: False)
+ **filters: Additional filtering options (merged with above parameters)
Returns:
- TableData: Table data collection
+ TableData: Table data object with columns, rows, and metadata
"""
connector = DatabaseConnector("", **self.config)
engine = connector.connect(connection_string)
try:
+ # Merge filters with explicit parameters
+ export_options = {
+ "limit": limit or filters.get("limit"),
+ "offset": offset or filters.get("offset"),
+ "where": where or filters.get("where"),
+ "order_by": order_by or filters.get("order_by")
+ }
+ # Remove None values
+ export_options = {k: v for k, v in export_options.items() if v is not None}
+
+ # Export table data
table_data = self.exporter.export_table_data(
engine,
table_name,
schema=schema,
- **filters
+ **export_options
)
# Transform data if requested
- if filters.get("transform", False):
+ if transform or filters.get("transform", False):
schema_info = {"columns": table_data.columns}
table_data.rows = self.exporter.transform_data(table_data.rows, schema_info)
+ self.logger.debug(f"Applied transformations to table {table_name}")
return table_data
finally:
connector.disconnect()
- def analyze_schema(self, connection_string: str, schema: Optional[str] = None) -> Dict[str, Any]:
+ def analyze_schema(
+ self,
+ connection_string: str,
+ schema: Optional[str] = None
+ ) -> Dict[str, Any]:
"""
Analyze database schema and structure.
+ This method exports the database schema and performs additional analysis
+ including table counts, view counts, and foreign key relationships.
+
Args:
connection_string: Database connection string
- schema: Schema name (optional)
+ schema: Schema name (for databases with schema support, optional)
Returns:
- dict: Schema analysis results
+ dict: Schema analysis dictionary containing:
+ - tables: List of table information
+ - views: List of view names
+ - foreign_keys: List of foreign key constraints
+ - analysis: Analysis summary with counts and statistics
"""
connector = DatabaseConnector("", **self.config)
engine = connector.connect(connection_string)
try:
+ # Export base schema information
schema_info = self.exporter.export_schema(engine, schema=schema)
- # Additional analysis
+ # Perform additional analysis
schema_info["analysis"] = {
"total_tables": len(schema_info["tables"]),
"total_views": len(schema_info["views"]),
"total_foreign_keys": len(schema_info["foreign_keys"]),
"tables_with_foreign_keys": len(set(
- fk["referred_table"] for fk in schema_info["foreign_keys"]
+ fk.get("referred_table", "") for fk in schema_info["foreign_keys"]
+ if fk.get("referred_table")
))
}
+ self.logger.info(
+ f"Schema analysis completed: {schema_info['analysis']['total_tables']} table(s), "
+ f"{schema_info['analysis']['total_views']} view(s)"
+ )
+
return schema_info
finally:
diff --git a/semantica/ingest/email_ingestor.py b/semantica/ingest/email_ingestor.py
index 3f5b10a1..8f3c9bea 100644
--- a/semantica/ingest/email_ingestor.py
+++ b/semantica/ingest/email_ingestor.py
@@ -1,19 +1,32 @@
"""
Email Ingestion Module
-Handles email protocol processing and content extraction.
+This module provides comprehensive email ingestion capabilities for the
+Semantica framework, enabling email retrieval, parsing, and content extraction
+from various email protocols.
Key Features:
- - IMAP/POP3 email retrieval
- - Email content parsing
- - Attachment processing
- - Email metadata extraction
- - Thread analysis
+ - IMAP/POP3 email retrieval with secure connections
+ - Email content parsing (plain text and HTML)
+ - Attachment processing and extraction
+ - Email metadata extraction (headers, dates, addresses)
+ - Thread analysis and conversation grouping
+ - Link extraction from email content
Main Classes:
- EmailIngestor: Main email ingestion class
- EmailParser: Email content parser
- AttachmentProcessor: Email attachment handler
+
+Example Usage:
+ >>> from semantica.ingest import EmailIngestor
+ >>> ingestor = EmailIngestor()
+ >>> ingestor.connect_imap("imap.example.com", username="user", password="pass")
+ >>> emails = ingestor.ingest_mailbox("INBOX", max_emails=100)
+ >>> threads = ingestor.analyze_threads(emails)
+
+Author: Semantica Contributors
+License: MIT
"""
import email
@@ -35,7 +48,25 @@ from ..utils.logging import get_logger
@dataclass
class EmailData:
- """Email data representation."""
+ """
+ Email data representation.
+
+ This dataclass represents a structured email message with all relevant
+ metadata, content, and attachments.
+
+ Attributes:
+ message_id: Unique message identifier
+ subject: Email subject line
+ from_address: Sender email address
+ to_addresses: List of recipient email addresses
+ cc_addresses: List of CC recipient email addresses
+ date: Email date/time (optional)
+ body_text: Plain text email body
+ body_html: HTML email body
+ attachments: List of attachment information dictionaries
+ headers: Dictionary of email headers
+ thread_id: Thread/conversation identifier (optional)
+ """
message_id: str
subject: str
@@ -54,33 +85,56 @@ class AttachmentProcessor:
"""
Email attachment processing and extraction.
- Processes various attachment types,
- extracts text content from documents,
- and handles image and media attachments.
+ This class processes various email attachment types, extracts text content
+ from documents, and handles image and media attachments. Creates temporary
+ files for processing and provides cleanup functionality.
+
+ Example Usage:
+ >>> processor = AttachmentProcessor()
+ >>> info = processor.process_attachment(data, "document.pdf", "application/pdf")
+ >>> processor.cleanup_attachments([info["saved_path"]])
"""
def __init__(self, **config):
"""
Initialize attachment processor.
+ Sets up the processor with configuration and creates a temporary
+ directory for storing attachments.
+
Args:
- **config: Processor configuration
+ **config: Processor configuration options (currently unused)
"""
self.logger = get_logger("attachment_processor")
self.config = config
self.temp_dir = tempfile.mkdtemp(prefix="semantica_attachments_")
+ self.logger.debug(f"Attachment processor initialized: temp_dir={self.temp_dir}")
- def process_attachment(self, attachment_data: bytes, filename: str, content_type: str) -> Dict[str, Any]:
+ def process_attachment(
+ self,
+ attachment_data: bytes,
+ filename: str,
+ content_type: str
+ ) -> Dict[str, Any]:
"""
Process individual email attachment.
+ This method saves the attachment to a temporary file, extracts text
+ content if applicable (for text files and documents), and returns
+ comprehensive attachment information.
+
Args:
- attachment_data: Attachment content bytes
- filename: Attachment filename
- content_type: MIME content type
+ attachment_data: Attachment content as bytes
+ filename: Original attachment filename
+ content_type: MIME content type (e.g., "application/pdf", "text/plain")
Returns:
- dict: Attachment information
+ dict: Attachment information dictionary containing:
+ - filename: Original filename
+ - content_type: MIME content type
+ - size: File size in bytes
+ - saved_path: Path to saved temporary file (or None if save failed)
+ - text_content: Extracted text content (or None if not applicable)
"""
attachment_info = {
"filename": filename,
@@ -116,43 +170,66 @@ class AttachmentProcessor:
return attachment_info
- def extract_text_content(self, attachment_path: Path, file_type: str) -> Optional[str]:
+ def extract_text_content(
+ self,
+ attachment_path: Path,
+ file_type: str
+ ) -> Optional[str]:
"""
Extract text content from attachment.
+ This method attempts to extract text content from various document
+ types. Currently supports plain text files. PDF and Word document
+ extraction would require additional libraries (PyPDF2/pdfplumber for
+ PDF, python-docx for Word).
+
Args:
attachment_path: Path to attachment file
- file_type: File MIME type
+ file_type: File MIME type (e.g., "application/pdf", "text/plain")
Returns:
- str: Extracted text content or None
+ str: Extracted text content, or None if extraction is not supported
+ or fails
"""
try:
if file_type == 'application/pdf':
# PDF text extraction would require PyPDF2 or pdfplumber
- return None # Placeholder - would need PDF library
- elif file_type in ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
+ self.logger.debug("PDF text extraction not implemented (requires PyPDF2/pdfplumber)")
+ return None
+ elif file_type in [
+ 'application/msword',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
+ ]:
# Word document extraction would require python-docx
- return None # Placeholder - would need docx library
+ self.logger.debug("Word document extraction not implemented (requires python-docx)")
+ return None
elif file_type.startswith('text/'):
with open(attachment_path, 'r', encoding='utf-8', errors='ignore') as f:
- return f.read()
+ content = f.read()
+ self.logger.debug(f"Extracted {len(content)} characters from text file")
+ return content
except Exception as e:
self.logger.error(f"Failed to extract text from {attachment_path}: {e}")
return None
- def cleanup_attachments(self, attachment_paths: List[str]):
+ def cleanup_attachments(self, attachment_paths: Optional[List[str]] = None):
"""
Clean up temporary attachment files.
+ This method removes the temporary directory and all files within it.
+ The attachment_paths parameter is currently unused but reserved for
+ selective cleanup in the future.
+
Args:
- attachment_paths: List of attachment file paths
+ attachment_paths: List of attachment file paths (optional, currently
+ unused - entire temp directory is cleaned)
"""
import shutil
try:
if Path(self.temp_dir).exists():
shutil.rmtree(self.temp_dir)
+ self.logger.debug(f"Cleaned up attachment directory: {self.temp_dir}")
except Exception as e:
self.logger.error(f"Failed to cleanup attachments: {e}")
@@ -161,31 +238,46 @@ class EmailParser:
"""
Email content parsing and extraction.
- Parses email headers and metadata,
- extracts email body content,
- handles MIME multipart messages,
- and processes HTML and plain text content.
+ This class parses email headers and metadata, extracts email body content
+ from both plain text and HTML parts, handles MIME multipart messages, and
+ extracts links from email content.
+
+ Example Usage:
+ >>> parser = EmailParser()
+ >>> headers = parser.parse_headers(email_message)
+ >>> body = parser.parse_body(email_message)
+ >>> links = parser.extract_links(body["html"])
"""
def __init__(self, **config):
"""
Initialize email parser.
+ Sets up the parser with configuration options.
+
Args:
- **config: Parser configuration
+ **config: Parser configuration options (currently unused)
"""
self.logger = get_logger("email_parser")
self.config = config
- def parse_headers(self, email_message: email.message.Message) -> Dict[str, str]:
+ def parse_headers(
+ self,
+ email_message: email.message.Message
+ ) -> Dict[str, str]:
"""
Parse email headers and metadata.
+ This method extracts all email headers, decodes them if necessary
+ (handling encoded headers with character sets), and returns them as
+ a dictionary with lowercase keys.
+
Args:
- email_message: Email message object
+ email_message: Email message object from email library
Returns:
- dict: Header dictionary
+ dict: Dictionary mapping header names (lowercase) to decoded
+ header values
"""
headers = {}
@@ -202,15 +294,24 @@ class EmailParser:
return headers
- def parse_body(self, email_message: email.message.Message) -> Dict[str, str]:
+ def parse_body(
+ self,
+ email_message: email.message.Message
+ ) -> Dict[str, str]:
"""
Parse email body content.
+ This method extracts both plain text and HTML content from email
+ messages, handling both multipart and single-part messages. Skips
+ attachment parts when extracting body content.
+
Args:
- email_message: Email message object
+ email_message: Email message object from email library
Returns:
- dict: Body content dictionary with 'text' and 'html' keys
+ dict: Body content dictionary with:
+ - text: Plain text email body (empty string if not available)
+ - html: HTML email body (empty string if not available)
"""
body = {"text": "", "html": ""}
@@ -264,11 +365,15 @@ class EmailParser:
"""
Extract links from email content.
+ This method extracts URLs from email content, supporting both HTML
+ (extracts href attributes from anchor tags) and plain text (uses
+ regex pattern matching). Removes duplicate URLs.
+
Args:
- email_content: Email content (HTML or text)
+ email_content: Email content (HTML or plain text)
Returns:
- list: List of extracted links
+ list: List of unique extracted URLs
"""
links = []
@@ -295,30 +400,36 @@ class EmailIngestor:
"""
Email protocol ingestion handler.
- Connects to email servers via IMAP/POP3,
- retrieves emails from mailboxes,
- and processes email content and attachments.
+ This class provides comprehensive email ingestion capabilities, connecting
+ to email servers via IMAP/POP3, retrieving emails from mailboxes, and
+ processing email content and attachments.
- Attributes:
- imap_client: IMAP client for email access
- pop3_client: POP3 client for email access
- parser: Email content parser
- attachment_processor: Attachment handling system
-
- Methods:
- ingest_mailbox(): Ingest emails from mailbox
- process_email(): Process individual email
- extract_attachments(): Extract email attachments
- analyze_threads(): Analyze email threads
+ Features:
+ - IMAP and POP3 protocol support
+ - Secure connections (SSL/TLS)
+ - Email filtering and pagination
+ - Thread analysis
+ - Attachment extraction
+
+ Example Usage:
+ >>> ingestor = EmailIngestor()
+ >>> ingestor.connect_imap("imap.example.com", username="user", password="pass")
+ >>> emails = ingestor.ingest_mailbox("INBOX", max_emails=100, unread_only=True)
+ >>> threads = ingestor.analyze_threads(emails)
+ >>> ingestor.disconnect()
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize email ingestor.
+ Sets up the ingestor with email parser and attachment processor.
+ Connection to email servers must be established separately using
+ connect_imap() or connect_pop3().
+
Args:
- config: Email ingestion configuration
- **kwargs: Additional configuration parameters
+ config: Optional email ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
"""
self.logger = get_logger("email_ingestor")
self.config = config or {}
@@ -333,74 +444,146 @@ class EmailIngestor:
# Connection objects (initialized on connect)
self.imap_client: Optional[imaplib.IMAP4_SSL] = None
self.pop3_client: Optional[poplib.POP3_SSL] = None
+
+ self.logger.debug("Email ingestor initialized")
- def connect_imap(self, server: str, port: int = 993, username: str = None, password: str = None):
+ def connect_imap(
+ self,
+ server: str,
+ port: int = 993,
+ username: Optional[str] = None,
+ password: Optional[str] = None
+ ):
"""
Connect to IMAP server.
+ This method establishes a secure SSL connection to an IMAP server and
+ authenticates with the provided credentials. The connection is stored
+ for use in subsequent operations.
+
Args:
- server: IMAP server address
- port: IMAP server port (default: 993)
- username: Email username
- password: Email password
+ server: IMAP server address (hostname or IP)
+ port: IMAP server port (default: 993 for SSL)
+ username: Email username (optional, can be provided later)
+ password: Email password (optional, can be provided later)
+
+ Raises:
+ ProcessingError: If connection or authentication fails
"""
try:
self.imap_client = imaplib.IMAP4_SSL(server, port)
if username and password:
self.imap_client.login(username, password)
- self.logger.info(f"Connected to IMAP server: {server}")
+ self.logger.info(f"Connected and authenticated to IMAP server: {server}:{port}")
+ else:
+ self.logger.info(f"Connected to IMAP server: {server}:{port} (not authenticated)")
except Exception as e:
self.logger.error(f"Failed to connect to IMAP: {e}")
- raise ProcessingError(f"Failed to connect to IMAP server: {e}")
+ raise ProcessingError(f"Failed to connect to IMAP server: {e}") from e
- def connect_pop3(self, server: str, port: int = 995, username: str = None, password: str = None):
+ def connect_pop3(
+ self,
+ server: str,
+ port: int = 995,
+ username: Optional[str] = None,
+ password: Optional[str] = None
+ ):
"""
Connect to POP3 server.
+ This method establishes a secure SSL connection to a POP3 server and
+ authenticates with the provided credentials. The connection is stored
+ for use in subsequent operations.
+
Args:
- server: POP3 server address
- port: POP3 server port (default: 995)
- username: Email username
- password: Email password
+ server: POP3 server address (hostname or IP)
+ port: POP3 server port (default: 995 for SSL)
+ username: Email username (optional, can be provided later)
+ password: Email password (optional, can be provided later)
+
+ Raises:
+ ProcessingError: If connection or authentication fails
"""
try:
self.pop3_client = poplib.POP3_SSL(server, port)
if username and password:
self.pop3_client.user(username)
self.pop3_client.pass_(password)
- self.logger.info(f"Connected to POP3 server: {server}")
+ self.logger.info(f"Connected and authenticated to POP3 server: {server}:{port}")
+ else:
+ self.logger.info(f"Connected to POP3 server: {server}:{port} (not authenticated)")
except Exception as e:
self.logger.error(f"Failed to connect to POP3: {e}")
- raise ProcessingError(f"Failed to connect to POP3 server: {e}")
+ raise ProcessingError(f"Failed to connect to POP3 server: {e}") from e
- def ingest_mailbox(self, mailbox_name: str = "INBOX", protocol: str = "imap", **filters) -> List[EmailData]:
+ def ingest_mailbox(
+ self,
+ mailbox_name: str = "INBOX",
+ protocol: str = "imap",
+ since: Optional[str] = None,
+ max_emails: Optional[int] = None,
+ unread_only: bool = False,
+ **filters
+ ) -> List[EmailData]:
"""
Ingest emails from specified mailbox.
+ This method retrieves emails from a mailbox using the specified
+ protocol (IMAP or POP3), applies optional filters, and returns
+ processed email data.
+
Args:
- mailbox_name: Mailbox name (default: "INBOX")
- protocol: Protocol to use ("imap" or "pop3")
- **filters: Email filtering criteria:
- - since: Date to start from
- - max_emails: Maximum number of emails
- - unread_only: Only fetch unread emails
+ mailbox_name: Mailbox name (default: "INBOX", IMAP only)
+ protocol: Protocol to use ("imap" or "pop3", default: "imap")
+ since: Date to start from (IMAP only, format: "DD-MMM-YYYY")
+ max_emails: Maximum number of emails to retrieve (optional)
+ unread_only: Only fetch unread emails (IMAP only, default: False)
+ **filters: Additional filtering criteria (merged with above)
Returns:
- list: Processed email collection
+ list: List of EmailData objects representing processed emails
+
+ Raises:
+ ProcessingError: If protocol is unsupported or client not connected
+ ValidationError: If protocol is invalid
"""
+ # Merge explicit parameters with filters
+ merged_filters = {
+ "since": since or filters.get("since"),
+ "max_emails": max_emails or filters.get("max_emails"),
+ "unread_only": unread_only or filters.get("unread_only", False)
+ }
+ # Remove None values
+ merged_filters = {k: v for k, v in merged_filters.items() if v is not None}
+
if protocol.lower() == "imap":
if not self.imap_client:
raise ProcessingError("IMAP client not connected. Call connect_imap() first.")
- return self._ingest_imap(mailbox_name, **filters)
+ return self._ingest_imap(mailbox_name, **merged_filters)
elif protocol.lower() == "pop3":
if not self.pop3_client:
raise ProcessingError("POP3 client not connected. Call connect_pop3() first.")
- return self._ingest_pop3(**filters)
+ return self._ingest_pop3(**merged_filters)
else:
- raise ValidationError(f"Unsupported protocol: {protocol}")
+ raise ValidationError(f"Unsupported protocol: {protocol}. Supported: 'imap', 'pop3'")
def _ingest_imap(self, mailbox_name: str, **filters) -> List[EmailData]:
- """Ingest emails using IMAP."""
+ """
+ Ingest emails using IMAP protocol.
+
+ This private method handles IMAP-specific email retrieval, including
+ mailbox selection, search criteria building, and email fetching.
+
+ Args:
+ mailbox_name: Name of the mailbox to access
+ **filters: Email filtering criteria (since, max_emails, unread_only)
+
+ Returns:
+ list: List of EmailData objects
+
+ Raises:
+ ProcessingError: If mailbox access or email retrieval fails
+ """
try:
# Select mailbox
self.imap_client.select(mailbox_name)
@@ -443,7 +626,21 @@ class EmailIngestor:
raise ProcessingError(f"Failed to ingest mailbox: {e}")
def _ingest_pop3(self, **filters) -> List[EmailData]:
- """Ingest emails using POP3."""
+ """
+ Ingest emails using POP3 protocol.
+
+ This private method handles POP3-specific email retrieval. POP3 does
+ not support mailbox selection or advanced filtering like IMAP.
+
+ Args:
+ **filters: Email filtering criteria (max_emails supported)
+
+ Returns:
+ list: List of EmailData objects
+
+ Raises:
+ ProcessingError: If email retrieval fails
+ """
try:
# Get email list
num_messages = len(self.pop3_client.list()[1])
@@ -469,15 +666,22 @@ class EmailIngestor:
self.logger.error(f"Error ingesting POP3: {e}")
raise ProcessingError(f"Failed to ingest POP3: {e}")
- def process_email(self, email_message: email.message.Message) -> EmailData:
+ def process_email(
+ self,
+ email_message: email.message.Message
+ ) -> EmailData:
"""
Process individual email message.
+ This method extracts all relevant information from an email message,
+ including headers, body content, attachments, and thread information.
+
Args:
- email_message: Email message object
+ email_message: Email message object from email library
Returns:
- EmailData: Structured email data
+ EmailData: Structured email data object with all extracted
+ information
"""
# Parse headers
headers = self.parser.parse_headers(email_message)
@@ -522,15 +726,27 @@ class EmailIngestor:
thread_id=thread_id
)
- def extract_attachments(self, email_message: email.message.Message) -> List[Dict[str, Any]]:
+ def extract_attachments(
+ self,
+ email_message: email.message.Message
+ ) -> List[Dict[str, Any]]:
"""
Extract and process email attachments.
+ This method walks through the email message parts, identifies
+ attachments (based on Content-Disposition header), decodes filenames,
+ and processes each attachment using the attachment processor.
+
Args:
- email_message: Email message object
+ email_message: Email message object from email library
Returns:
- list: Attachment information
+ list: List of attachment information dictionaries, each containing:
+ - filename: Attachment filename
+ - content_type: MIME content type
+ - size: File size in bytes
+ - saved_path: Path to saved temporary file
+ - text_content: Extracted text content (if applicable)
"""
attachments = []
@@ -564,11 +780,22 @@ class EmailIngestor:
"""
Analyze email threads and conversations.
+ This method groups emails into threads based on thread IDs (from
+ In-Reply-To or References headers) or message IDs, and analyzes
+ thread characteristics including participants and message counts.
+
Args:
- emails: List of email data objects
+ emails: List of EmailData objects to analyze
Returns:
- dict: Thread analysis results
+ dict: Thread analysis dictionary containing:
+ - total_threads: Total number of unique threads
+ - threads: List of thread dictionaries, each containing:
+ - thread_id: Thread identifier
+ - emails: List of emails in the thread
+ - participants: List of participant email addresses
+ - subject: Thread subject (from first email)
+ - message_count: Number of messages in thread
"""
threads = {}
@@ -599,7 +826,19 @@ class EmailIngestor:
}
def _parse_address_list(self, address_string: str) -> List[str]:
- """Parse email address list string into list of addresses."""
+ """
+ Parse email address list string into list of addresses.
+
+ This private method parses email address strings (which may contain
+ multiple addresses in various formats) into a list of email addresses.
+ Uses email.utils for proper parsing, with regex fallback.
+
+ Args:
+ address_string: Email address string (may contain multiple addresses)
+
+ Returns:
+ list: List of email addresses
+ """
if not address_string:
return []
@@ -617,7 +856,12 @@ class EmailIngestor:
return addresses
def disconnect(self):
- """Disconnect from email servers."""
+ """
+ Disconnect from email servers.
+
+ This method closes all active connections (IMAP and POP3) and cleans
+ up resources. Should be called when done with email operations.
+ """
if self.imap_client:
try:
self.imap_client.close()
diff --git a/semantica/ingest/feed_ingestor.py b/semantica/ingest/feed_ingestor.py
index fc5056aa..81b0ca4e 100644
--- a/semantica/ingest/feed_ingestor.py
+++ b/semantica/ingest/feed_ingestor.py
@@ -1,19 +1,31 @@
"""
Feed Ingestion Module
-Handles RSS, Atom, and other feed format processing.
+This module provides comprehensive feed ingestion capabilities for the
+Semantica framework, enabling RSS, Atom, and other feed format processing,
+discovery, and monitoring.
Key Features:
- - RSS/Atom feed parsing
- - Feed discovery
- - Content extraction
- - Update monitoring
+ - RSS/Atom feed parsing with format auto-detection
+ - Feed discovery from websites
+ - Content extraction from feed items
+ - Update monitoring with callbacks
- Feed validation
+ - Date parsing with multiple format support
Main Classes:
- FeedIngestor: Main feed ingestion class
- FeedParser: Feed format parser
- FeedMonitor: Feed update monitoring
+
+Example Usage:
+ >>> from semantica.ingest import FeedIngestor
+ >>> ingestor = FeedIngestor()
+ >>> feed_data = ingestor.ingest_feed("https://example.com/feed.xml")
+ >>> feeds = ingestor.discover_feeds("https://example.com")
+
+Author: Semantica Contributors
+License: MIT
"""
import time
@@ -33,7 +45,23 @@ from ..utils.logging import get_logger
@dataclass
class FeedItem:
- """Feed item representation."""
+ """
+ Feed item representation.
+
+ This dataclass represents a single item/entry from an RSS or Atom feed.
+
+ Attributes:
+ title: Item title
+ link: Item URL
+ description: Item description/summary
+ content: Full item content (if available)
+ author: Item author (optional)
+ published: Publication date (optional)
+ updated: Last update date (optional)
+ guid: Unique identifier for the item
+ categories: List of category tags
+ metadata: Additional metadata dictionary
+ """
title: str
link: str
@@ -49,7 +77,20 @@ class FeedItem:
@dataclass
class FeedData:
- """Feed data representation."""
+ """
+ Feed data representation.
+
+ This dataclass represents a complete RSS or Atom feed with all its items.
+
+ Attributes:
+ title: Feed title
+ link: Feed URL
+ description: Feed description
+ language: Feed language code
+ updated: Last feed update date (optional)
+ items: List of FeedItem objects
+ metadata: Additional feed metadata dictionary
+ """
title: str
link: str
@@ -64,30 +105,47 @@ class FeedParser:
"""
Feed format parser for RSS, Atom, and other formats.
- Handles parsing of various feed formats with
- unified content extraction.
+ This class handles parsing of various feed formats with unified content
+ extraction. Auto-detects feed format and parses accordingly.
+
+ Example Usage:
+ >>> parser = FeedParser()
+ >>> feed_data = parser.parse_feed(xml_content, feed_url="https://example.com/feed.xml")
+ >>> is_valid = parser.validate_feed(feed_data)
"""
def __init__(self, **config):
"""
Initialize feed parser.
+ Sets up the parser with configuration options.
+
Args:
- **config: Parser configuration
+ **config: Parser configuration options (currently unused)
"""
self.logger = get_logger("feed_parser")
self.config = config
- def parse_feed(self, feed_content: str, feed_url: Optional[str] = None) -> FeedData:
+ def parse_feed(
+ self,
+ feed_content: str,
+ feed_url: Optional[str] = None
+ ) -> FeedData:
"""
Parse feed content and extract items.
+ This method auto-detects the feed format (RSS or Atom) and parses
+ the content accordingly, extracting all feed metadata and items.
+
Args:
- feed_content: Raw feed content
- feed_url: Source feed URL
+ feed_content: Raw feed content (XML string)
+ feed_url: Source feed URL (optional, used for link resolution)
Returns:
- FeedData: Parsed feed data
+ FeedData: Parsed feed data object with all items and metadata
+
+ Raises:
+ ProcessingError: If feed parsing fails or format is unsupported
"""
try:
# Detect feed format
@@ -109,11 +167,14 @@ class FeedParser:
"""
Detect feed format from content.
+ This method analyzes the XML structure to determine whether the feed
+ is RSS or Atom format. Falls back to RSS if format is unclear.
+
Args:
- feed_content: Raw feed content
+ feed_content: Raw feed content (XML string)
Returns:
- str: Detected feed format (rss, atom)
+ str: Detected feed format ("rss" or "atom")
"""
try:
root = ET.fromstring(feed_content)
@@ -327,16 +388,26 @@ class FeedMonitor:
"""
Feed update monitoring and notification.
- Monitors feeds for updates and triggers processing
- when new content is available.
+ This class monitors feeds for updates and triggers processing when new
+ content is available. Runs in a background thread and supports callbacks
+ for new items.
+
+ Example Usage:
+ >>> monitor = FeedMonitor(check_interval=1800) # 30 minutes
+ >>> monitor.add_feed("https://example.com/feed.xml")
+ >>> monitor.set_update_callback(lambda url, items: print(f"New items: {len(items)}"))
+ >>> monitor.start_monitoring()
"""
def __init__(self, **config):
"""
Initialize feed monitor.
+ Sets up the monitor with configuration and initializes monitoring state.
+
Args:
- **config: Monitor configuration
+ **config: Monitor configuration options:
+ - check_interval: Interval between checks in seconds (default: 3600)
"""
self.logger = get_logger("feed_monitor")
self.config = config
@@ -462,28 +533,32 @@ class FeedIngestor:
"""
RSS/Atom feed ingestion handler.
- Processes RSS, Atom, and other feed formats with
- support for content extraction and monitoring.
+ This class provides comprehensive feed ingestion capabilities, processing
+ RSS, Atom, and other feed formats with support for content extraction
+ and monitoring.
- Attributes:
- parser: Feed format parser
- monitor: Feed update monitor
- content_extractor: Content extraction engine
-
- Methods:
- ingest_feed(): Ingest single feed
- discover_feeds(): Discover feeds from website
- monitor_feeds(): Monitor multiple feeds
- extract_content(): Extract content from feed items
+ Features:
+ - RSS and Atom feed parsing
+ - Feed discovery from websites
+ - Feed update monitoring
+ - Content extraction from feed items
+
+ Example Usage:
+ >>> ingestor = FeedIngestor()
+ >>> feed_data = ingestor.ingest_feed("https://example.com/feed.xml")
+ >>> feeds = ingestor.discover_feeds("https://example.com")
+ >>> monitor = ingestor.monitor_feeds(feeds, check_interval=1800)
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize feed ingestor.
+ Sets up the ingestor with feed parser and monitor.
+
Args:
- config: Feed ingestion configuration
- **kwargs: Additional configuration parameters
+ config: Optional feed ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
"""
self.logger = get_logger("feed_ingestor")
self.config = config or {}
@@ -497,17 +572,34 @@ class FeedIngestor:
# Update intervals
self.update_intervals = self.config.get("update_intervals", {})
+
+ self.logger.debug("Feed ingestor initialized")
- def ingest_feed(self, feed_url: str, **options) -> FeedData:
+ def ingest_feed(
+ self,
+ feed_url: str,
+ timeout: Optional[int] = None,
+ validate: bool = True,
+ **options
+ ) -> FeedData:
"""
Ingest content from a single feed.
+ This method fetches a feed from the provided URL, parses it, and
+ optionally validates it. Handles both RSS and Atom formats.
+
Args:
feed_url: URL of feed to ingest
- **options: Processing options
+ timeout: Request timeout in seconds (optional, default: 30)
+ validate: Whether to validate the parsed feed (default: True)
+ **options: Additional processing options (unused)
Returns:
- FeedData: Parsed feed content
+ FeedData: Parsed feed content object with all items and metadata
+
+ Raises:
+ ValidationError: If feed URL is invalid
+ ProcessingError: If feed fetching or parsing fails
"""
# Validate feed URL
try:
@@ -519,32 +611,38 @@ class FeedIngestor:
# Fetch feed content
try:
- timeout = options.get("timeout", self.config.get("timeout", 30))
- response = requests.get(feed_url, timeout=timeout)
+ 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}")
+ 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 options.get("validate", True):
+ 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
def discover_feeds(self, website_url: str) -> List[str]:
"""
Discover feeds from a website.
+ This method scans a website for feed links, checking both HTML link
+ tags and common feed paths. Validates discovered feeds by attempting
+ to fetch them.
+
Args:
- website_url: Website URL to scan
+ website_url: Website URL to scan for feeds
Returns:
- list: List of discovered feed URLs
+ list: List of discovered and validated feed URLs
"""
feed_urls = []
diff --git a/semantica/ingest/file_ingestor.py b/semantica/ingest/file_ingestor.py
index 48aecfb3..c0f6d4b5 100644
--- a/semantica/ingest/file_ingestor.py
+++ b/semantica/ingest/file_ingestor.py
@@ -1,19 +1,25 @@
"""
File Ingestion Module
-Handles ingestion from local filesystem and cloud storage providers.
+This module provides comprehensive file ingestion capabilities from local filesystems
+and cloud storage providers, with automatic file type detection and validation.
Key Features:
- - Local file system scanning
- - Cloud storage integration (S3, GCS, Azure)
- - File type detection
- - Batch processing
- - Progress tracking
+ - Local file system scanning (recursive and filtered)
+ - Cloud storage integration (AWS S3, Google Cloud Storage, Azure Blob)
+ - Automatic file type detection (extension, MIME type, magic numbers)
+ - Batch processing with progress tracking
+ - File size validation and limits
+ - Support for all common document, image, audio, and video formats
-Main Classes:
- - FileIngestor: Main file ingestion class
- - CloudStorageIngestor: Cloud storage specific handling
- - FileTypeDetector: File type identification
+Example Usage:
+ >>> from semantica.ingest import FileIngestor
+ >>> ingestor = FileIngestor()
+ >>> files = ingestor.ingest_directory("./documents", recursive=True)
+ >>> file = ingestor.ingest_file("document.pdf", read_content=True)
+
+Author: Semantica Contributors
+License: MIT
"""
import mimetypes
@@ -52,76 +58,120 @@ class FileTypeDetector:
"""
File type detection and validation.
- Identifies file types using multiple methods including
- extension, MIME type, and content analysis.
+ This class identifies file types using multiple detection methods:
+ 1. File extension analysis
+ 2. MIME type detection
+ 3. Magic number (file signature) analysis
+
+ It supports a wide range of document, image, audio, and video formats.
"""
def __init__(self):
- """Initialize file type detector."""
+ """
+ Initialize file type detector.
+
+ Sets up the detector with all supported file formats and initializes
+ the MIME types database for accurate type detection.
+ """
self.logger = get_logger("file_type_detector")
+
+ # Combine all supported formats into a single list
self.supported_formats = (
SUPPORTED_DOCUMENT_FORMATS +
SUPPORTED_IMAGE_FORMATS +
SUPPORTED_AUDIO_FORMATS +
SUPPORTED_VIDEO_FORMATS
)
- # Initialize MIME types database
+
+ # Initialize Python's MIME types database
mimetypes.init()
+
+ self.logger.debug(f"File type detector initialized with {len(self.supported_formats)} supported formats")
def detect_type(self, file_path: Union[str, Path], content: Optional[bytes] = None) -> str:
"""
- Detect file type using multiple methods.
+ Detect file type using multiple detection methods.
+
+ This method tries three detection strategies in order:
+ 1. File extension (fastest, most common)
+ 2. MIME type detection (if file exists)
+ 3. Magic number analysis (most reliable, requires content)
Args:
- file_path: Path to file
- content: Optional file content
+ file_path: Path to file (can be string or Path object)
+ content: Optional file content bytes for magic number detection
Returns:
- str: Detected file type
+ str: Detected file type (extension without dot, e.g., "pdf", "jpg")
+ Returns "unknown" if type cannot be determined
"""
file_path = Path(file_path)
- # Method 1: Check file extension
+ # Method 1: Check file extension (fastest method)
extension = file_path.suffix.lstrip('.').lower()
if extension:
+ self.logger.debug(f"Detected file type by extension: {extension}")
return extension
- # Method 2: Check MIME type
+ # Method 2: Check MIME type (if file exists on filesystem)
if file_path.exists():
mime_type, _ = mimetypes.guess_type(str(file_path))
if mime_type:
- # Map MIME type to extension
+ # Convert MIME type to file extension
ext = mimetypes.guess_extension(mime_type)
if ext:
- return ext.lstrip('.').lower()
+ detected_type = ext.lstrip('.').lower()
+ self.logger.debug(f"Detected file type by MIME type: {detected_type}")
+ return detected_type
- # Method 3: Check magic numbers if content provided
+ # Method 3: Check magic numbers (file signatures) if content provided
+ # This is the most reliable method but requires reading file content
if content:
file_type = self._detect_by_magic_numbers(content)
if file_type:
+ self.logger.debug(f"Detected file type by magic numbers: {file_type}")
return file_type
+ # Could not determine file type
+ self.logger.warning(f"Could not determine file type for: {file_path}")
return "unknown"
def _detect_by_magic_numbers(self, content: bytes) -> Optional[str]:
- """Detect file type by magic numbers (file signatures)."""
+ """
+ Detect file type by analyzing magic numbers (file signatures).
+
+ Magic numbers are specific byte sequences at the beginning of files
+ that uniquely identify the file format. This is the most reliable
+ detection method but requires file content.
+
+ Args:
+ content: File content bytes (at least first few bytes)
+
+ Returns:
+ str: Detected file type or None if not recognized
+ """
+ # Need at least 4 bytes for most magic number checks
if len(content) < 4:
return None
- # Common magic numbers
+ # Dictionary of magic numbers (file signatures) mapped to file types
+ # Format: {magic_bytes: file_extension}
magic_numbers = {
- b'\x25\x50\x44\x46': 'pdf', # PDF
- b'\x50\x4B\x03\x04': 'zip', # ZIP/DOCX/XLSX/PPTX
- b'\x89\x50\x4E\x47': 'png', # PNG
- b'\xFF\xD8\xFF': 'jpg', # JPEG
- b'\x47\x49\x46\x38': 'gif', # GIF
- b'%PDF': 'pdf', # PDF (text)
+ b'\x25\x50\x44\x46': 'pdf', # PDF (binary)
+ b'%PDF': 'pdf', # PDF (text header)
+ b'\x50\x4B\x03\x04': 'zip', # ZIP, DOCX, XLSX, PPTX (Office Open XML)
+ b'\x89\x50\x4E\x47': 'png', # PNG image
+ b'\xFF\xD8\xFF': 'jpg', # JPEG image
+ b'\x47\x49\x46\x38': 'gif', # GIF image
+ b'PK\x03\x04': 'zip', # ZIP (alternative)
}
- for magic, file_type in magic_numbers.items():
- if content.startswith(magic):
+ # Check if content starts with any known magic number
+ for magic_bytes, file_type in magic_numbers.items():
+ if content.startswith(magic_bytes):
return file_type
+ # No matching magic number found
return None
def is_supported(self, file_type: str) -> bool:
@@ -297,42 +347,51 @@ class FileIngestor:
"""
File system and cloud storage ingestion handler.
- Supports local files, cloud storage (S3, GCS, Azure), and
- various file formats with automatic type detection.
+ This class provides comprehensive file ingestion capabilities from:
+ - Local filesystem (files and directories)
+ - Cloud storage providers (AWS S3, Google Cloud Storage, Azure Blob)
+
+ Features:
+ - Automatic file type detection
+ - Recursive directory scanning
+ - File size validation
+ - Progress tracking callbacks
+ - Batch processing with error handling
- Attributes:
- config: Ingestion configuration
- supported_formats: List of supported file formats
- cloud_providers: Available cloud storage providers
-
- Methods:
- ingest_directory(): Ingest entire directory
- ingest_file(): Ingest single file
- ingest_cloud(): Ingest from cloud storage
- scan_directory(): Scan directory for files
+ Example Usage:
+ >>> ingestor = FileIngestor()
+ >>> files = ingestor.ingest_directory("./documents", recursive=True)
+ >>> single_file = ingestor.ingest_file("report.pdf", read_content=True)
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize file ingestor.
+ Sets up the ingestor with configuration and initializes the file type
+ detector. Cloud storage providers are initialized lazily when needed.
+
Args:
- config: Ingestion configuration
- **kwargs: Additional configuration parameters
+ config: Ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
"""
self.logger = get_logger("file_ingestor")
+
+ # Merge configuration
self.config = config or {}
self.config.update(kwargs)
- # Initialize file type detector
+ # Initialize file type detector for automatic format detection
self.type_detector = FileTypeDetector()
self.supported_formats = self.type_detector.supported_formats
- # Cloud providers (lazy initialization)
+ # Cloud storage providers (initialized on-demand for better performance)
self._cloud_providers: Dict[str, CloudStorageIngestor] = {}
- # Progress tracking
- self._progress_callback = None
+ # Progress tracking callback (can be set by user)
+ self._progress_callback: Optional[callable] = None
+
+ self.logger.info("File ingestor initialized")
def ingest_directory(
self,
@@ -387,52 +446,71 @@ class FileIngestor:
def ingest_file(self, file_path: Union[str, Path], **options) -> FileObject:
"""
- Ingest a single file.
+ Ingest a single file from the filesystem.
+
+ This method reads a file, detects its type, validates its size,
+ and creates a FileObject with all relevant metadata.
Args:
- file_path: Path to file
- **options: Processing options
-
+ file_path: Path to the file to ingest (string or Path object)
+ **options: Processing options:
+ - read_content: Whether to read file content (default: True)
+ - Additional metadata to include in FileObject
+
Returns:
- FileObject: Ingested file object
+ FileObject: Ingested file object with metadata and optional content
+
+ Raises:
+ ValidationError: If file doesn't exist, isn't a file, or exceeds size limits
+ ProcessingError: If file cannot be read
"""
file_path = Path(file_path)
- # Validate 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 limits
+ # Check file size against limits
file_size = file_path.stat().st_size
- max_size = FILE_SIZE_LIMITS.get('MAX_DOCUMENT_SIZE', 104857600)
+ max_size = FILE_SIZE_LIMITS.get('MAX_DOCUMENT_SIZE', 104857600) # 100MB default
if file_size > max_size:
- raise ValidationError(f"File size {file_size} exceeds maximum {max_size}")
+ raise ValidationError(
+ f"File size {file_size:,} bytes exceeds maximum {max_size:,} bytes "
+ f"({file_path.name})"
+ )
- # Detect file type
+ # 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_path}")
+ self.logger.warning(
+ f"Unsupported file type '{file_type}' for file: {file_path}. "
+ "Processing may be limited."
+ )
- # Read file content if requested
+ # Read file content if requested (default: True)
content = None
- if options.get('read_content', True):
+ read_content = options.get('read_content', True)
+ if read_content:
try:
- with open(file_path, 'rb') as f:
- content = f.read()
+ 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: {e}")
- raise ProcessingError(f"Failed to read file: {e}")
+ self.logger.error(f"Failed to read file content from {file_path}: {e}")
+ raise ProcessingError(f"Failed to read file: {e}") from e
- # Get MIME type
+ # Detect MIME type for additional metadata
mime_type, _ = mimetypes.guess_type(str(file_path))
- # Create file object
+ # Create and return FileObject with all metadata
file_obj = FileObject(
- path=str(file_path),
+ path=str(file_path.absolute()),
name=file_path.name,
size=file_size,
file_type=file_type,
@@ -442,10 +520,12 @@ class FileIngestor:
'extension': file_path.suffix,
'parent': str(file_path.parent),
'is_supported': self.type_detector.is_supported(file_type),
- **options
+ 'read_content': read_content,
+ **options # Include any additional options as metadata
}
)
+ self.logger.debug(f"Successfully ingested file: {file_path.name} ({file_type})")
return file_obj
def ingest_cloud(
diff --git a/semantica/ingest/repo_ingestor.py b/semantica/ingest/repo_ingestor.py
index 0b6856f6..cf0243d0 100644
--- a/semantica/ingest/repo_ingestor.py
+++ b/semantica/ingest/repo_ingestor.py
@@ -1,19 +1,32 @@
"""
Repository Ingestion Module
-Handles Git repository processing and code analysis.
+This module provides comprehensive Git repository ingestion capabilities for the
+Semantica framework, enabling repository cloning, code analysis, and commit
+history processing.
Key Features:
- Git repository cloning and analysis
- - Code file extraction
- - Commit history processing
+ - Code file extraction with language detection
+ - Commit history processing and analysis
- Branch and tag analysis
- - Code structure analysis
+ - Code structure analysis (classes, functions, imports)
+ - Dependency analysis
+ - Documentation extraction
Main Classes:
- RepoIngestor: Main repository ingestion class
- GitAnalyzer: Git repository analyzer
- CodeExtractor: Code content extractor
+
+Example Usage:
+ >>> from semantica.ingest import RepoIngestor
+ >>> ingestor = RepoIngestor()
+ >>> repo_data = ingestor.ingest_repository("https://github.com/user/repo.git")
+ >>> commits = ingestor.analyze_commits(repo_path, max_commits=100)
+
+Author: Semantica Contributors
+License: MIT
"""
import os
@@ -33,7 +46,21 @@ from ..utils.logging import get_logger
@dataclass
class CodeFile:
- """Code file representation."""
+ """
+ Code file representation.
+
+ This dataclass represents a code file with its content, metadata, and
+ structural information.
+
+ Attributes:
+ path: File path relative to repository root
+ name: File name
+ language: Detected programming language
+ content: File content as string
+ size: File size in bytes
+ lines: Number of lines in file
+ metadata: Additional metadata (extension, modification date, structure)
+ """
path: str
name: str
@@ -46,7 +73,20 @@ class CodeFile:
@dataclass
class CommitInfo:
- """Commit information representation."""
+ """
+ Commit information representation.
+
+ This dataclass represents a Git commit with its metadata and statistics.
+
+ Attributes:
+ hash: Commit hash (short form)
+ message: Commit message
+ author: Commit author
+ date: Commit date
+ files_changed: List of files changed in commit
+ additions: Number of lines added
+ deletions: Number of lines deleted
+ """
hash: str
message: str
@@ -61,8 +101,15 @@ class CodeExtractor:
"""
Code content extraction and processing.
- Extracts code content from various file types
- and processes different programming languages.
+ This class extracts code content from various file types, detects
+ programming languages, extracts structure (classes, functions), and
+ analyzes dependencies.
+
+ Example Usage:
+ >>> extractor = CodeExtractor()
+ >>> code_file = extractor.extract_file_content(Path("file.py"))
+ >>> docs = extractor.extract_documentation(Path("file.py"))
+ >>> deps = extractor.analyze_dependencies(Path("file.py"))
"""
# File extension to language mapping
@@ -289,16 +336,23 @@ class GitAnalyzer:
"""
Git repository analysis and statistics.
- Analyzes repository structure and history,
- calculates code metrics and statistics.
+ This class analyzes repository structure and history, calculates code
+ metrics and statistics, and detects code patterns.
+
+ Example Usage:
+ >>> analyzer = GitAnalyzer()
+ >>> structure = analyzer.analyze_structure(repo_path)
+ >>> metrics = analyzer.calculate_metrics(repo_path)
"""
def __init__(self, **config):
"""
Initialize Git analyzer.
+ Sets up the analyzer with configuration options.
+
Args:
- **config: Analyzer configuration
+ **config: Analyzer configuration options (currently unused)
"""
self.logger = get_logger("git_analyzer")
self.config = config
@@ -402,21 +456,25 @@ class RepoIngestor:
"""
Git repository ingestion handler.
- Clones and analyzes Git repositories,
- extracts code files and documentation,
- and processes commit history and metadata.
+ This class provides comprehensive Git repository ingestion capabilities,
+ cloning repositories, extracting code files and documentation, and
+ processing commit history and metadata.
- Attributes:
- git_client: Git client for repository operations
- code_extractor: Code content extraction engine
- analyzer: Repository analysis tools
- supported_platforms: List of supported Git platforms
-
- Methods:
- ingest_repository(): Clone and process repository
- analyze_commits(): Analyze commit history
- extract_code_files(): Extract and process code files
- get_repository_info(): Get repository metadata
+ Features:
+ - Repository cloning from various platforms
+ - Code file extraction with filtering
+ - Commit history analysis
+ - Repository structure and metrics analysis
+ - Branch and tag information
+
+ Example Usage:
+ >>> ingestor = RepoIngestor()
+ >>> repo_data = ingestor.ingest_repository(
+ ... "https://github.com/user/repo.git",
+ ... branch="main",
+ ... include_history=True
+ ... )
+ >>> ingestor.cleanup()
"""
SUPPORTED_PLATFORMS = ['github', 'gitlab', 'bitbucket', 'generic']
@@ -425,9 +483,12 @@ class RepoIngestor:
"""
Initialize repository ingestor.
+ Sets up the ingestor with code extractor and analyzer. Note that
+ the `git` library must be installed for this module to work.
+
Args:
- config: Repository ingestion configuration
- **kwargs: Additional configuration parameters
+ config: Optional repository ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
"""
self.logger = get_logger("repo_ingestor")
self.config = config or {}
@@ -441,6 +502,8 @@ class RepoIngestor:
# Temporary directory for cloning
self.temp_dir = None
+
+ self.logger.debug("Repo ingestor initialized")
def ingest_repository(self, repo_url: str, **options) -> Dict[str, Any]:
"""
diff --git a/semantica/ingest/stream_ingestor.py b/semantica/ingest/stream_ingestor.py
index 7ae31df9..ed864fe5 100644
--- a/semantica/ingest/stream_ingestor.py
+++ b/semantica/ingest/stream_ingestor.py
@@ -1,20 +1,37 @@
"""
Stream Ingestion Module
-Handles real-time data stream processing from various sources.
+This module provides comprehensive real-time data stream processing capabilities
+for the Semantica framework, supporting multiple streaming platforms and
+protocols.
Key Features:
- Kafka stream processing
- - Pulsar integration
+ - Apache Pulsar integration
- RabbitMQ message handling
- - Kinesis stream processing
- - Real-time data transformation
- - Stream monitoring
+ - AWS Kinesis stream processing
+ - Real-time data transformation and validation
+ - Stream health monitoring and metrics
+ - Error handling and retry logic
Main Classes:
- StreamIngestor: Main stream ingestion class
- - StreamProcessor: Stream data processor
+ - StreamProcessor: Base stream data processor
+ - KafkaProcessor: Kafka-specific processor
+ - RabbitMQProcessor: RabbitMQ-specific processor
+ - KinesisProcessor: AWS Kinesis-specific processor
+ - PulsarProcessor: Apache Pulsar-specific processor
- StreamMonitor: Stream health monitoring
+
+Example Usage:
+ >>> from semantica.ingest import StreamIngestor
+ >>> ingestor = StreamIngestor()
+ >>> processor = ingestor.ingest_kafka("topic", ["localhost:9092"])
+ >>> processor.set_message_handler(lambda msg: print(msg))
+ >>> processor.start_consuming()
+
+Author: Semantica Contributors
+License: MIT
"""
import json
@@ -30,7 +47,20 @@ from ..utils.logging import get_logger
@dataclass
class StreamMessage:
- """Stream message representation."""
+ """
+ Stream message representation.
+
+ This dataclass represents a message from a streaming source with its
+ content, metadata, and position information.
+
+ Attributes:
+ content: Message content (any type)
+ metadata: Message metadata dictionary
+ timestamp: Message timestamp
+ source: Source identifier
+ partition: Partition number (for partitioned streams, optional)
+ offset: Message offset (optional)
+ """
content: Any
metadata: Dict[str, Any] = field(default_factory=dict)
@@ -44,17 +74,25 @@ class StreamProcessor:
"""
Generic stream data processor.
- Base class for processing data from various
- streaming sources with common functionality.
+ This is the base class for processing data from various streaming sources
+ with common functionality including message transformation, validation,
+ error handling, and statistics tracking.
+
+ Subclasses should implement `_consume_loop()` for source-specific
+ consumption logic.
"""
def __init__(self, source_config: Dict[str, Any], **options):
"""
Initialize stream processor.
+ Sets up the processor with source configuration and processing options.
+
Args:
- source_config: Source-specific configuration
- **options: Processing options
+ source_config: Source-specific configuration dictionary
+ **options: Processing options:
+ - transform: Optional transformation function for messages
+ - validate: Optional validation function for messages
"""
self.logger = get_logger("stream_processor")
self.source_config = source_config
@@ -492,29 +530,34 @@ class StreamIngestor:
"""
Real-time stream ingestion handler.
- Processes data streams from various sources with
- support for different streaming protocols.
-
- Attributes:
- processors: Dictionary of stream processors
- monitor: Stream health monitor
- config: Stream configuration
-
- Methods:
- ingest_kafka(): Ingest from Kafka streams
- ingest_pulsar(): Ingest from Pulsar streams
- ingest_rabbitmq(): Ingest from RabbitMQ
- ingest_kinesis(): Ingest from Kinesis
- start_streaming(): Start stream processing
+ This class provides comprehensive stream ingestion capabilities, processing
+ data streams from various sources with support for different streaming
+ protocols (Kafka, Pulsar, RabbitMQ, Kinesis).
+
+ Features:
+ - Multiple streaming platform support
+ - Stream health monitoring
+ - Error handling and recovery
+ - Message transformation and validation
+
+ Example Usage:
+ >>> ingestor = StreamIngestor()
+ >>> kafka_proc = ingestor.ingest_kafka("topic", ["localhost:9092"])
+ >>> kafka_proc.set_message_handler(process_message)
+ >>> ingestor.start_streaming()
+ >>> health = ingestor.monitor.check_health()
"""
def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
Initialize stream ingestor.
+ Sets up the ingestor with stream monitor. Processors are created
+ dynamically when ingesting from specific sources.
+
Args:
- config: Stream ingestion configuration
- **kwargs: Additional configuration parameters
+ config: Optional stream ingestion configuration dictionary
+ **kwargs: Additional configuration parameters (merged into config)
"""
self.logger = get_logger("stream_ingestor")
self.config = config or {}
@@ -525,6 +568,8 @@ class StreamIngestor:
# Setup stream monitor
self.monitor = StreamMonitor(**self.config)
+
+ self.logger.debug("Stream ingestor initialized")
def ingest_kafka(self, topic: str, bootstrap_servers: List[str], **options) -> KafkaProcessor:
"""
diff --git a/semantica/ingest/web_ingestor.py b/semantica/ingest/web_ingestor.py
index 7e3d34ea..762666c1 100644
--- a/semantica/ingest/web_ingestor.py
+++ b/semantica/ingest/web_ingestor.py
@@ -1,20 +1,34 @@
"""
Web Ingestion Module
-Handles web scraping, crawling, and content extraction from websites.
+This module provides comprehensive web scraping, crawling, and content extraction
+capabilities for the Semantica framework, enabling ingestion from websites and
+web-based sources.
Key Features:
- - HTTP/HTTPS content fetching
- - Sitemap crawling
+ - HTTP/HTTPS content fetching with retry logic
+ - Sitemap crawling and URL discovery
- RSS/Atom feed processing
- - JavaScript rendering
- - Rate limiting and politeness
- - Content extraction
+ - JavaScript rendering support (via optional dependencies)
+ - Rate limiting and robots.txt compliance
+ - Content extraction and cleaning
+ - Link discovery and domain crawling
Main Classes:
- WebIngestor: Main web ingestion class
- SitemapCrawler: Sitemap-based crawling
- ContentExtractor: Web content extraction
+ - RateLimiter: Request rate limiting
+ - RobotsChecker: Robots.txt compliance checker
+
+Example Usage:
+ >>> from semantica.ingest import WebIngestor
+ >>> ingestor = WebIngestor(delay=1.0, respect_robots=True)
+ >>> content = ingestor.ingest_url("https://example.com")
+ >>> pages = ingestor.crawl_sitemap("https://example.com/sitemap.xml")
+
+Author: Semantica Contributors
+License: MIT
"""
import time
@@ -50,35 +64,66 @@ class WebContent:
class RateLimiter:
- """Simple rate limiter for web requests."""
+ """
+ Simple rate limiter for web requests.
+
+ This class enforces a minimum delay between web requests to ensure
+ polite crawling behavior and avoid overwhelming target servers.
+
+ Example Usage:
+ >>> limiter = RateLimiter(delay=1.0)
+ >>> limiter.wait_if_needed() # Waits if needed before request
+ """
def __init__(self, delay: float = 1.0):
"""
Initialize rate limiter.
+ Sets up the rate limiter with a specified delay between requests.
+
Args:
- delay: Delay between requests in seconds
+ delay: Minimum delay between requests in seconds (default: 1.0)
"""
self.delay = delay
self.last_request_time: float = 0.0
def wait_if_needed(self):
- """Wait if necessary to respect rate limit."""
+ """
+ Wait if necessary to respect rate limit.
+
+ This method calculates the time elapsed since the last request and
+ sleeps if necessary to maintain the minimum delay between requests.
+ """
elapsed = time.time() - self.last_request_time
if elapsed < self.delay:
- time.sleep(self.delay - elapsed)
+ sleep_time = self.delay - elapsed
+ time.sleep(sleep_time)
self.last_request_time = time.time()
class RobotsChecker:
- """Robots.txt compliance checker."""
+ """
+ Robots.txt compliance checker.
+
+ This class checks robots.txt files to determine if URLs can be fetched
+ according to the website's crawling policies. Caches parsed robots.txt
+ files per domain for efficiency.
+
+ Example Usage:
+ >>> checker = RobotsChecker(user_agent="MyBot/1.0")
+ >>> if checker.can_fetch("https://example.com/page"):
+ ... # Fetch the page
+ """
def __init__(self, user_agent: str = "SemanticaBot/1.0"):
"""
Initialize robots checker.
+ Sets up the checker with a user agent string for robots.txt compliance.
+
Args:
- user_agent: User agent string
+ user_agent: User agent string to use for robots.txt checks
+ (default: "SemanticaBot/1.0")
"""
self.user_agent = user_agent
self.parsers: Dict[str, RobotFileParser] = {}
@@ -87,31 +132,39 @@ class RobotsChecker:
"""
Check if URL can be fetched according to robots.txt.
+ This method checks the robots.txt file for the URL's domain to determine
+ if the specified user agent is allowed to fetch the URL. Caches parsed
+ robots.txt files for efficiency.
+
Args:
- url: URL to check
+ url: URL to check for fetch permission
Returns:
- bool: True if can fetch, False otherwise
+ bool: True if URL can be fetched, False if blocked by robots.txt
"""
parsed = urlparse(url)
domain = f"{parsed.scheme}://{parsed.netloc}"
+ # Check if we already have a parser for this domain
if domain not in self.parsers:
# Create robots.txt URL
robots_url = urljoin(domain, "/robots.txt")
- # Create parser
+ # Create and configure parser
parser = RobotFileParser()
parser.set_url(robots_url)
try:
parser.read()
except Exception:
- # If robots.txt not available, assume allowed
+ # If robots.txt not available or unreadable, assume allowed
+ # (per robots.txt spec: if file doesn't exist, all access is allowed)
pass
+ # Cache parser for this domain
self.parsers[domain] = parser
+ # Check permission using cached parser
parser = self.parsers[domain]
return parser.can_fetch(self.user_agent, url)
@@ -120,74 +173,101 @@ class ContentExtractor:
"""
Web content extraction and cleaning.
- Extracts text, metadata, and structured data from
- web pages with various extraction strategies.
+ This class extracts text, metadata, and structured data from web pages
+ using various extraction strategies. Handles HTML parsing, text cleaning,
+ and metadata extraction.
+
+ Example Usage:
+ >>> extractor = ContentExtractor()
+ >>> text = extractor.extract_text(html_content)
+ >>> metadata = extractor.extract_metadata(html_content, url="https://example.com")
"""
def __init__(self, **config):
"""
Initialize content extractor.
+ Sets up the extractor with configuration options.
+
Args:
- **config: Extraction configuration
+ **config: Extraction configuration options (currently unused)
"""
self.logger = get_logger("content_extractor")
self.config = config
def extract_text(self, html_content: str) -> str:
"""
- Extract clean text from HTML.
+ Extract clean text from HTML content.
+
+ This method removes script and style elements, extracts text content,
+ and cleans up whitespace to produce readable text.
Args:
- html_content: HTML content
+ html_content: Raw HTML content string
Returns:
- str: Extracted text content
+ str: Cleaned text content extracted from HTML
"""
soup = BeautifulSoup(html_content, 'html.parser')
- # Remove script and style elements
+ # Remove script and style elements (not useful for text extraction)
for element in soup(['script', 'style']):
element.decompose()
- # Extract text
+ # Extract text content
text = soup.get_text()
- # Clean whitespace
+ # Clean whitespace: split into lines, strip each, then split on double spaces
lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
text = ' '.join(chunk for chunk in chunks if chunk)
return text
- def extract_metadata(self, html_content: str, url: Optional[str] = None) -> Dict[str, Any]:
+ def extract_metadata(
+ self,
+ html_content: str,
+ url: Optional[str] = None
+ ) -> Dict[str, Any]:
"""
- Extract metadata from HTML.
+ Extract metadata from HTML content.
+
+ This method extracts various metadata from HTML including:
+ - Page title
+ - Meta tags (description, keywords, etc.)
+ - Open Graph data (og:title, og:description, etc.)
+ - Source URL
Args:
- html_content: HTML content
- url: Source URL
+ html_content: Raw HTML content string
+ url: Source URL for the page (optional)
Returns:
- dict: Extracted metadata
+ dict: Extracted metadata dictionary with keys:
+ - url: Source URL (if provided)
+ - title: Page title
+ - description: Meta description (if available)
+ - keywords: Meta keywords (if available)
+ - og: Open Graph data dictionary (if available)
+ - Additional meta tag values
"""
metadata = {'url': url} if url else {}
soup = BeautifulSoup(html_content, 'html.parser')
- # Extract title
+ # Extract page title
title_tag = soup.find('title')
if title_tag:
metadata['title'] = title_tag.get_text().strip()
- # Extract meta tags
+ # Extract standard meta tags
for meta_tag in soup.find_all('meta'):
name = meta_tag.get('name') or meta_tag.get('property')
content = meta_tag.get('content')
if name and content:
metadata[name.lower()] = content
- # Extract Open Graph data
+ # Extract Open Graph data (for social media sharing)
og_data = {}
for meta_tag in soup.find_all('meta', property=re.compile(r'^og:')):
property_name = meta_tag.get('property', '').replace('og:', '')
@@ -200,31 +280,39 @@ class ContentExtractor:
return metadata
- def extract_links(self, html_content: str, base_url: Optional[str] = None) -> List[str]:
+ def extract_links(
+ self,
+ html_content: str,
+ base_url: Optional[str] = None
+ ) -> List[str]:
"""
- Extract links from HTML.
+ Extract links from HTML content.
+
+ This method extracts all hyperlinks from HTML, resolves relative URLs
+ to absolute URLs, and filters to only include HTTP/HTTPS links.
Args:
- html_content: HTML content
- base_url: Base URL for relative links
+ html_content: Raw HTML content string
+ base_url: Base URL for resolving relative links (optional)
Returns:
- list: List of extracted links
+ list: List of extracted absolute URLs (HTTP/HTTPS only)
"""
links = []
soup = BeautifulSoup(html_content, 'html.parser')
+ # Extract all anchor tags with href attributes
for link_tag in soup.find_all('a', href=True):
href = link_tag['href']
- # Resolve relative URLs
+ # Resolve relative URLs to absolute URLs
if base_url:
link = urljoin(base_url, href)
else:
link = href
- # Filter valid links
+ # Filter to only include HTTP/HTTPS links
parsed = urlparse(link)
if parsed.scheme in ('http', 'https'):
links.append(link)
@@ -236,16 +324,24 @@ class SitemapCrawler:
"""
Sitemap-based web crawling.
- Specialized crawler for processing XML sitemaps and
- extracting URLs for processing.
+ This class provides specialized functionality for processing XML sitemaps
+ and extracting URLs for web crawling. Supports both standard sitemaps
+ and sitemap index files.
+
+ Example Usage:
+ >>> crawler = SitemapCrawler()
+ >>> urls = crawler.parse_sitemap("https://example.com/sitemap.xml")
+ >>> all_urls = crawler.crawl_sitemap_index("https://example.com/sitemap_index.xml")
"""
def __init__(self, **config):
"""
Initialize sitemap crawler.
+ Sets up the crawler with configuration options.
+
Args:
- **config: Crawler configuration
+ **config: Crawler configuration options (currently unused)
"""
self.logger = get_logger("sitemap_crawler")
self.config = config
@@ -254,77 +350,96 @@ class SitemapCrawler:
"""
Parse sitemap and extract URLs.
+ This method fetches and parses an XML sitemap, extracting all URLs
+ listed in the sitemap. Supports both namespaced and non-namespaced
+ sitemap formats.
+
Args:
- sitemap_url: URL of sitemap
+ sitemap_url: URL of the sitemap XML file
Returns:
- list: List of URLs from sitemap
+ list: List of URLs extracted from the sitemap
+
+ Raises:
+ ProcessingError: If sitemap cannot be fetched or parsed
"""
try:
+ # Fetch sitemap
response = requests.get(sitemap_url, timeout=30)
response.raise_for_status()
+ # Parse XML
root = ET.fromstring(response.content)
- # Namespace handling
+ # Standard sitemap namespace
namespaces = {
'sitemap': 'http://www.sitemaps.org/schemas/sitemap/0.9'
}
urls = []
- # Extract URLs from urlset
+ # Extract URLs from urlset (namespaced format)
for url_elem in root.findall('.//sitemap:url', namespaces):
loc_elem = url_elem.find('sitemap:loc', namespaces)
if loc_elem is not None and loc_elem.text:
urls.append(loc_elem.text.strip())
- # Also handle non-namespaced sitemaps
+ # Also handle non-namespaced sitemaps (fallback)
if not urls:
for url_elem in root.findall('.//url'):
loc_elem = url_elem.find('loc')
if loc_elem is not None and loc_elem.text:
urls.append(loc_elem.text.strip())
+ self.logger.debug(f"Extracted {len(urls)} URL(s) from sitemap: {sitemap_url}")
return urls
except Exception as e:
self.logger.error(f"Failed to parse sitemap {sitemap_url}: {e}")
- raise ProcessingError(f"Failed to parse sitemap: {e}")
+ raise ProcessingError(f"Failed to parse sitemap: {e}") from e
def crawl_sitemap_index(self, index_url: str) -> List[str]:
"""
Crawl sitemap index and all referenced sitemaps.
+ This method fetches a sitemap index file, extracts references to
+ individual sitemaps, and parses each referenced sitemap to collect
+ all URLs. Useful for large websites with multiple sitemap files.
+
Args:
- index_url: URL of sitemap index
+ index_url: URL of the sitemap index XML file
Returns:
- list: List of all URLs from all sitemaps
+ list: List of all URLs from all referenced sitemaps
+
+ Raises:
+ ProcessingError: If sitemap index cannot be fetched or parsed
"""
try:
+ # Fetch sitemap index
response = requests.get(index_url, timeout=30)
response.raise_for_status()
+ # Parse XML
root = ET.fromstring(response.content)
- # Namespace handling
+ # Standard sitemap namespace
namespaces = {
'sitemap': 'http://www.sitemaps.org/schemas/sitemap/0.9'
}
all_urls = []
- # Find sitemap references
+ # Find sitemap references (namespaced format)
for sitemap_elem in root.findall('.//sitemap:sitemap', namespaces):
loc_elem = sitemap_elem.find('sitemap:loc', namespaces)
if loc_elem is not None and loc_elem.text:
sitemap_url = loc_elem.text.strip()
- # Parse the referenced sitemap
+ # Parse each referenced sitemap
urls = self.parse_sitemap(sitemap_url)
all_urls.extend(urls)
- # Also handle non-namespaced sitemaps
+ # Also handle non-namespaced sitemaps (fallback)
if not all_urls:
for sitemap_elem in root.findall('.//sitemap'):
loc_elem = sitemap_elem.find('loc')
@@ -333,133 +448,203 @@ class SitemapCrawler:
urls = self.parse_sitemap(sitemap_url)
all_urls.extend(urls)
+ self.logger.debug(
+ f"Extracted {len(all_urls)} URL(s) from sitemap index: {index_url}"
+ )
return all_urls
except Exception as e:
self.logger.error(f"Failed to crawl sitemap index {index_url}: {e}")
- raise ProcessingError(f"Failed to crawl sitemap index: {e}")
+ raise ProcessingError(f"Failed to crawl sitemap index: {e}") from e
class WebIngestor:
"""
Web content ingestion handler.
- Fetches and processes content from websites with support
- for various protocols and content types.
+ This class provides comprehensive web content ingestion capabilities including
+ single URL fetching, sitemap crawling, and domain-wide crawling. Includes
+ rate limiting, robots.txt compliance, and content extraction.
+
+ Features:
+ - HTTP/HTTPS content fetching with retry logic
+ - Sitemap crawling and URL discovery
+ - Domain-wide crawling with link following
+ - Rate limiting and politeness
+ - Robots.txt compliance checking
+ - Content extraction and cleaning
- Attributes:
- session: HTTP session for requests
- rate_limiter: Rate limiting controller
- content_extractor: Content extraction engine
- robots_checker: Robots.txt compliance checker
-
- Methods:
- ingest_url(): Ingest single URL
- crawl_sitemap(): Crawl sitemap
- crawl_domain(): Crawl entire domain
- extract_content(): Extract content from page
+ Example Usage:
+ >>> ingestor = WebIngestor(
+ ... delay=1.0,
+ ... respect_robots=True,
+ ... max_retries=3
+ ... )
+ >>> content = ingestor.ingest_url("https://example.com")
+ >>> pages = ingestor.crawl_sitemap("https://example.com/sitemap.xml")
"""
- def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ def __init__(
+ self,
+ user_agent: str = "SemanticaBot/1.0",
+ delay: float = 1.0,
+ respect_robots: bool = True,
+ max_retries: int = 3,
+ backoff_factor: float = 1.0,
+ timeout: int = 30,
+ config: Optional[Dict[str, Any]] = None,
+ **kwargs
+ ):
"""
Initialize web ingestor.
+ Sets up the ingestor with HTTP session, rate limiting, content extraction,
+ and robots.txt compliance checking.
+
Args:
- config: Web ingestion configuration
+ user_agent: User agent string for HTTP requests (default: "SemanticaBot/1.0")
+ delay: Minimum delay between requests in seconds (default: 1.0)
+ respect_robots: Whether to respect robots.txt (default: True)
+ max_retries: Maximum number of retry attempts (default: 3)
+ backoff_factor: Backoff factor for retries (default: 1.0)
+ timeout: Request timeout in seconds (default: 30)
+ config: Optional configuration dictionary (merged with kwargs)
**kwargs: Additional configuration parameters
"""
self.logger = get_logger("web_ingestor")
self.config = config or {}
self.config.update(kwargs)
- # Initialize HTTP session
+ # Initialize HTTP session with retry strategy
self.session = requests.Session()
# Configure user agent
- user_agent = self.config.get('user_agent', 'SemanticaBot/1.0')
+ user_agent = user_agent or self.config.get('user_agent', 'SemanticaBot/1.0')
self.session.headers.update({'User-Agent': user_agent})
- # Setup retry strategy
+ # Setup retry strategy for transient errors
retry_strategy = Retry(
- total=self.config.get('max_retries', 3),
- backoff_factor=self.config.get('backoff_factor', 1),
- status_forcelist=[429, 500, 502, 503, 504],
+ total=max_retries,
+ backoff_factor=backoff_factor,
+ status_forcelist=[429, 500, 502, 503, 504], # Retry on these status codes
)
adapter = HTTPAdapter(max_retries=retry_strategy)
self.session.mount("http://", adapter)
self.session.mount("https://", adapter)
# Setup rate limiting
- delay = self.config.get('delay', 1.0)
self.rate_limiter = RateLimiter(delay=delay)
# Initialize content extractor
self.content_extractor = ContentExtractor(**self.config)
- # Setup robots checker
- respect_robots = self.config.get('respect_robots', True)
+ # Setup robots checker if requested
if respect_robots:
self.robots_checker = RobotsChecker(user_agent=user_agent)
else:
self.robots_checker = None
+
+ self.logger.debug(
+ f"Web ingestor initialized: user_agent={user_agent}, "
+ f"delay={delay}, respect_robots={respect_robots}"
+ )
- def ingest_url(self, url: str, **options) -> WebContent:
+ def ingest_url(
+ self,
+ url: str,
+ timeout: Optional[int] = None,
+ **options
+ ) -> WebContent:
"""
Ingest content from a single URL.
+ This method fetches content from a URL, checks robots.txt compliance,
+ applies rate limiting, and extracts content and metadata.
+
Args:
- url: URL to ingest
- **options: Processing options
+ url: URL to ingest (must be HTTP or HTTPS)
+ timeout: Request timeout in seconds (default: self.config timeout or 30)
+ **options: Additional processing options (unused)
Returns:
- WebContent: Extracted web content
+ WebContent: Extracted web content with text, HTML, metadata, and links
+
+ Raises:
+ ValidationError: If URL is invalid
+ ProcessingError: If URL is blocked by robots.txt or fetch fails
"""
- # Validate URL
+ # Validate URL format
try:
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
- raise ValidationError(f"Invalid URL: {url}")
+ 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
+ # 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
+ # Apply rate limiting (wait if necessary)
self.rate_limiter.wait_if_needed()
- # Fetch content
+ # Fetch content with retry logic
try:
- timeout = options.get('timeout', self.config.get('timeout', 30))
- response = self.session.get(url, timeout=timeout)
+ 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}")
+ raise ProcessingError(f"Failed to fetch URL: {e}") from e
- # Extract content
+ # 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)}"
+ )
+
return web_content
- def crawl_sitemap(self, sitemap_url: str, **filters) -> List[WebContent]:
+ def crawl_sitemap(
+ self,
+ sitemap_url: str,
+ max_urls: Optional[int] = None,
+ fail_fast: bool = False,
+ **filters
+ ) -> List[WebContent]:
"""
Crawl URLs from sitemap.
+ This method parses a sitemap (or sitemap index), extracts URLs, applies
+ filters, and ingests content from each URL. Supports both standard sitemaps
+ and sitemap index files.
+
Args:
- sitemap_url: URL of sitemap
- **filters: URL filtering criteria
-
+ sitemap_url: URL of the sitemap XML file
+ max_urls: Maximum number of URLs to crawl (default: None, crawl all)
+ fail_fast: Whether to stop on first error (default: False)
+ **filters: URL filtering criteria:
+ - pattern: Regex pattern to match URLs
+ - domains: List of allowed domains
+ - exclude_pattern: Regex pattern to exclude URLs
+
Returns:
- list: List of web content objects
+ list: List of WebContent objects for successfully crawled URLs
+
+ Raises:
+ ProcessingError: If sitemap cannot be parsed or fail_fast=True and error occurs
"""
crawler = SitemapCrawler(**self.config)
- # Parse sitemap
+ # Parse sitemap (try as regular sitemap first, then as index)
try:
urls = crawler.parse_sitemap(sitemap_url)
except Exception as e:
@@ -467,104 +652,153 @@ class WebIngestor:
try:
urls = crawler.crawl_sitemap_index(sitemap_url)
except Exception:
- raise ProcessingError(f"Failed to parse sitemap: {e}")
+ raise ProcessingError(f"Failed to parse sitemap: {e}") from e
+
+ self.logger.debug(f"Found {len(urls)} URL(s) in sitemap: {sitemap_url}")
- # Apply filters
+ # 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 = filters.get('max_urls', self.config.get('max_urls'))
+ 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
try:
web_content = self.ingest_url(url)
web_contents.append(web_content)
- self.logger.debug(f"Crawled URL {idx+1}/{len(urls)}: {url}")
+ 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 self.config.get('fail_fast', False):
- raise ProcessingError(f"Failed to crawl 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
- def crawl_domain(self, domain: str, max_pages: int = 100, **options) -> List[WebContent]:
+ def crawl_domain(
+ self,
+ domain: str,
+ max_pages: int = 100,
+ fail_fast: bool = False,
+ **options
+ ) -> List[WebContent]:
"""
Crawl entire domain starting from root.
+ This method performs a breadth-first crawl of a domain, starting from
+ the root URL and following links within the same domain. Maintains a
+ visited set to avoid duplicate crawling.
+
Args:
- domain: Domain to crawl
- max_pages: Maximum pages to crawl
- **options: Crawling options
+ domain: Domain to crawl (with or without http/https prefix)
+ max_pages: Maximum number of pages to crawl (default: 100)
+ fail_fast: Whether to stop on first error (default: False)
+ **options: Additional crawling options (unused)
Returns:
- list: List of web content objects
+ list: List of WebContent objects for successfully crawled pages
+
+ Raises:
+ ProcessingError: If fail_fast=True and error occurs during crawling
"""
- # Normalize domain
+ # Normalize domain URL
if not domain.startswith(('http://', 'https://')):
domain = f"https://{domain}"
- # Start from domain root
+ # Initialize crawl state
visited: Set[str] = set()
to_visit: List[str] = [domain]
web_contents = []
+ self.logger.debug(f"Starting domain crawl: {domain}, max_pages={max_pages}")
+
+ # Breadth-first crawl
while to_visit and len(web_contents) < max_pages:
url = to_visit.pop(0)
+ # Skip if already visited
if url in visited:
continue
visited.add(url)
try:
+ # Ingest current URL
web_content = self.ingest_url(url)
web_contents.append(web_content)
- # Discover links
+ # Discover and queue links from same domain
+ parsed_domain = urlparse(domain)
for link in web_content.links:
parsed_link = urlparse(link)
- parsed_domain = urlparse(domain)
# Only follow links from same domain
if parsed_link.netloc == parsed_domain.netloc:
- if link not in visited:
+ if link not in visited and link not in to_visit:
to_visit.append(link)
- self.logger.debug(f"Crawled page {len(web_contents)}/{max_pages}: {url}")
+ self.logger.debug(
+ f"Crawled page {len(web_contents)}/{max_pages}: {url}, "
+ f"queued={len(to_visit)}"
+ )
except Exception as e:
self.logger.error(f"Failed to crawl URL {url}: {e}")
- if self.config.get('fail_fast', False):
- raise ProcessingError(f"Failed to crawl 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"Domain crawl completed: {len(web_contents)} page(s) crawled, "
+ f"{len(visited)} URL(s) visited"
+ )
return web_contents
- def extract_content(self, html_content: str, url: Optional[str] = None) -> WebContent:
+ def extract_content(
+ self,
+ html_content: str,
+ url: Optional[str] = None
+ ) -> WebContent:
"""
Extract content from HTML.
+ This method extracts text, metadata, and links from HTML content using
+ the content extractor. Creates a WebContent object with all extracted
+ information.
+
Args:
- html_content: HTML content to extract from
- url: Source URL for context
+ html_content: Raw HTML content string to extract from
+ url: Source URL for context (used for link resolution and metadata)
Returns:
- WebContent: Extracted content
+ WebContent: Extracted content object with:
+ - url: Source URL
+ - title: Page title
+ - text: Cleaned text content
+ - html: Original HTML content
+ - metadata: Extracted metadata dictionary
+ - links: List of extracted links
"""
- # Extract text content
+ # Extract text content (cleaned)
text = self.content_extractor.extract_text(html_content)
- # Extract metadata
+ # Extract metadata (title, meta tags, Open Graph, etc.)
metadata = self.content_extractor.extract_metadata(html_content, url=url)
- # Extract links
+ # Extract links (absolute URLs)
links = self.content_extractor.extract_links(html_content, base_url=url)
- # Get title
+ # Get title from metadata
title = metadata.get('title', '')
# Create web content object