Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Organize ingest folder structure with config, registry, and methods
KaifAhmad16f1f845c04ba
diff --git a/semantica/ingest/__init__.py b/semantica/ingest/__init__.pyindex 0298f382..9bc4a515 100644--- a/semantica/ingest/__init__.py+++ b/semantica/ingest/__init__.py@@ -1,9 +1,84 @@"""Data Ingestion Module-This module provides comprehensive data ingestion capabilities from various sources.+This module provides comprehensive data ingestion capabilities from various sources+including files, web content, feeds, streams, repositories, emails, and databases.-Exports:+Algorithms Used:++File Ingestion:+ - File Type Detection: Multi-method detection (extension-based, MIME type, magic number analysis)+ - Directory Scanning: Recursive directory traversal with filtering+ - Cloud Storage Integration: AWS S3, Google Cloud Storage, Azure Blob Storage API integration+ - File Validation: Size limits, format validation, content verification+ - Batch Processing: Parallel file processing with progress tracking+ - Magic Number Analysis: Binary file signature detection for accurate type identification++Web Ingestion:+ - HTTP Request Handling: GET/POST requests with retry logic and error handling+ - Rate Limiting: Time-based delay enforcement between requests+ - Robots.txt Compliance: RobotFileParser-based robots.txt checking and URL filtering+ - Content Extraction: BeautifulSoup-based HTML parsing and text extraction+ - Sitemap Crawling: XML sitemap parsing and URL discovery+ - Link Discovery: HTML link extraction and domain filtering+ - JavaScript Rendering: Optional Selenium/Playwright integration for dynamic content+ - URL Normalization: URL parsing, joining, and canonicalization++Feed Ingestion:+ - RSS/Atom Parsing: XML parsing with format auto-detection+ - Feed Discovery: HTML link tag parsing for feed discovery+ - Date Parsing: Multiple date format parsing (RFC 822, ISO 8601, etc.)+ - Feed Validation: XML schema validation and format verification+ - Update Monitoring: Polling-based feed update detection with callbacks+ - Content Extraction: Feed item content and metadata extraction++Stream Ingestion:+ - Kafka Processing: Kafka consumer group management and message processing+ - RabbitMQ Processing: AMQP protocol handling and queue management+ - AWS Kinesis Processing: Kinesis stream reading and shard management+ - Apache Pulsar Processing: Pulsar consumer and subscription management+ - Message Transformation: Custom transformation pipeline for stream messages+ - Error Handling: Retry logic, dead letter queue handling, error recovery+ - Stream Monitoring: Health checks, metrics collection, performance monitoring+ - Partition Management: Partition assignment and load balancing++Repository Ingestion:+ - Git Operations: Repository cloning, branch checking, commit traversal+ - Code Extraction: File content extraction with language detection+ - Commit Analysis: Git log parsing, diff analysis, statistics calculation+ - Language Detection: File extension and content-based programming language identification+ - Code Structure Analysis: AST parsing for classes, functions, imports extraction+ - Dependency Analysis: Package manager file parsing (requirements.txt, package.json, etc.)+ - Documentation Extraction: README, docstring, and comment extraction++Email Ingestion:+ - IMAP Protocol: IMAP connection, mailbox selection, message retrieval+ - POP3 Protocol: POP3 connection and message downloading+ - Email Parsing: RFC 822 email message parsing with header and body extraction+ - Attachment Processing: MIME attachment extraction and file saving+ - Content Extraction: Plain text and HTML body extraction with BeautifulSoup+ - Thread Analysis: Message-ID and In-Reply-To header-based conversation threading+ - Link Extraction: URL extraction from email HTML content++Database Ingestion:+ - Database Connection: SQLAlchemy-based connection management with connection pooling+ - SQL Query Execution: Parameterized query execution with result set processing+ - Schema Introspection: Database schema analysis and table/column discovery+ - Data Type Conversion: Database-specific type to Python type conversion+ - Pagination: Large dataset processing with LIMIT/OFFSET or cursor-based pagination+ - Data Export: Result set to dictionary/JSON conversion+ - Multi-database Support: PostgreSQL, MySQL, SQLite, Oracle, SQL Server abstraction++Key Features:+ - Multiple ingestion source types (file, web, feed, stream, repo, email, db)+ - Unified ingestion function with source type dispatch+ - Method registry for extensibility+ - Configuration management with environment variables and config files+ - Batch processing and progress tracking+ - Error handling and retry logic+ - Content extraction and transformation++Main Classes:- FileIngestor: Local and cloud file processing- WebIngestor: Web scraping and crawling- FeedIngestor: RSS/Atom feed processing@@ -11,7 +86,28 @@ Exports:- RepoIngestor: Git repository processing- EmailIngestor: Email protocol handling- DBIngestor: Database export handling+ - MethodRegistry: Registry for custom ingestion methods+ - IngestConfig: Configuration manager for ingest module++Convenience Functions:+ - ingest: Unified ingestion function with source type dispatch+ - ingest_file: File ingestion wrapper+ - ingest_web: Web ingestion wrapper+ - ingest_feed: Feed ingestion wrapper+ - ingest_stream: Stream ingestion wrapper+ - ingest_repository: Repository ingestion wrapper+ - ingest_email: Email ingestion wrapper+ - ingest_database: Database ingestion wrapper- build: Module-level build function for data ingestion++Example Usage:+ >>> from semantica.ingest import ingest, ingest_file, ingest_web+ >>> # Unified ingestion+ >>> result = ingest("document.pdf", source_type="file")+ >>> # File ingestion+ >>> files = ingest_file("./documents", method="directory")+ >>> # Web ingestion+ >>> content = ingest_web("https://example.com", method="url")"""from typing import Any, Dict, List, Optional, Union@@ -33,6 +129,20 @@ from .stream_ingestor import (from .repo_ingestor import RepoIngestor, CodeFile, CommitInfo, CodeExtractor, GitAnalyzerfrom .email_ingestor import EmailIngestor, EmailData, AttachmentProcessor, EmailParser as EmailIngestorParserfrom .db_ingestor import DBIngestor, TableData, DatabaseConnector, DataExporter+from .registry import MethodRegistry, method_registry+from .methods import (+ ingest,+ ingest_file,+ ingest_web,+ ingest_feed,+ ingest_stream,+ ingest_repository,+ ingest_email,+ ingest_database,+ get_ingest_method,+ list_available_methods,+)+from .config import IngestConfig, ingest_config__all__ = [# File ingestion@@ -78,6 +188,23 @@ __all__ = ["TableData","DatabaseConnector","DataExporter",+ # Registry and Methods+ "MethodRegistry",+ "method_registry",+ "ingest",+ "ingest_file",+ "ingest_web",+ "ingest_feed",+ "ingest_stream",+ "ingest_repository",+ "ingest_email",+ "ingest_database",+ "get_ingest_method",+ "list_available_methods",+ # Configuration+ "IngestConfig",+ "ingest_config",+ # Legacy"build",]diff --git a/semantica/ingest/config.py b/semantica/ingest/config.pynew file mode 100644index 00000000..17196bc0--- /dev/null+++ b/semantica/ingest/config.py@@ -0,0 +1,173 @@+"""+Configuration Management Module for Ingestion++This module provides centralized configuration management for data ingestion operations,+supporting multiple configuration sources including environment variables, config files,+and programmatic configuration.++Supported Configuration Sources:+ - Environment variables: INGEST_DEFAULT_SOURCE_TYPE, INGEST_MAX_FILE_SIZE, INGEST_RATE_LIMIT_DELAY, etc.+ - Config files: YAML, JSON, TOML formats+ - Programmatic: Python API for setting ingestion configurations++Algorithms Used:+ - Environment Variable Parsing: OS-level environment variable access+ - YAML Parsing: YAML parser for configuration file loading+ - JSON Parsing: JSON parser for configuration file loading+ - TOML Parsing: TOML parser for configuration file loading+ - Fallback Chain: Priority-based configuration resolution+ - Dictionary Merging: Deep merge algorithms for configuration updates++Key Features:+ - Environment variable support for ingestion parameters+ - Config file support (YAML, JSON, TOML formats)+ - Programmatic configuration via Python API+ - Method-specific configuration management+ - Automatic fallback chain (config file -> environment -> defaults)+ - Global config instance for easy access++Main Classes:+ - IngestConfig: Main configuration manager class for ingest module++Example Usage:+ >>> from semantica.ingest.config import ingest_config+ >>> source_type = ingest_config.get("default_source_type", default="file")+ >>> ingest_config.set("default_source_type", "web")+ >>> method_config = ingest_config.get_method_config("file")+"""++import os+from typing import Optional, Dict, Any+from pathlib import Path++from ..utils.logging import get_logger+++class IngestConfig:+ """Configuration manager for ingest module - supports .env files, environment variables, and programmatic config."""++ def __init__(self, config_file: Optional[str] = None):+ """Initialize configuration manager."""+ self.logger = get_logger("ingest_config")+ self._configs: Dict[str, Any] = {}+ self._method_configs: Dict[str, Dict] = {}+ self._load_config_file(config_file)+ self._load_env_vars()++ def _load_config_file(self, config_file: Optional[str]):+ """Load configuration from file."""+ if config_file and Path(config_file).exists():+ try:+ # Support YAML, JSON, TOML+ if config_file.endswith('.yaml') or config_file.endswith('.yml'):+ import yaml+ with open(config_file, 'r') as f:+ data = yaml.safe_load(f) or {}+ self._configs.update(data.get("ingest", {}))+ self._method_configs.update(data.get("ingest_methods", {}))+ elif config_file.endswith('.json'):+ import json+ with open(config_file, 'r') as f:+ data = json.load(f) or {}+ self._configs.update(data.get("ingest", {}))+ self._method_configs.update(data.get("ingest_methods", {}))+ elif config_file.endswith('.toml'):+ import toml+ with open(config_file, 'r') as f:+ data = toml.load(f) or {}+ if "ingest" in data:+ self._configs.update(data["ingest"])+ if "ingest_methods" in data:+ self._method_configs.update(data["ingest_methods"])+ self.logger.info(f"Loaded ingest config from {config_file}")+ except Exception as e:+ self.logger.warning(f"Failed to load config file {config_file}: {e}")++ def _load_env_vars(self):+ """Load configuration from environment variables."""+ # Ingestion-specific environment variables with INGEST_ prefix+ env_mappings = {+ "INGEST_DEFAULT_SOURCE_TYPE": ("default_source_type", str),+ "INGEST_MAX_FILE_SIZE": ("max_file_size", int),+ "INGEST_RECURSIVE": ("recursive", bool),+ "INGEST_READ_CONTENT": ("read_content", bool),+ "INGEST_RATE_LIMIT_DELAY": ("rate_limit_delay", float),+ "INGEST_RESPECT_ROBOTS": ("respect_robots", bool),+ "INGEST_BATCH_SIZE": ("batch_size", int),+ "INGEST_TIMEOUT": ("timeout", float),+ }++ for env_key, (config_key, type_func) in env_mappings.items():+ value = os.getenv(env_key)+ if value:+ try:+ if type_func == bool:+ self._configs[config_key] = value.lower() in ("true", "1", "yes", "on")+ else:+ self._configs[config_key] = type_func(value)+ except (ValueError, TypeError):+ self.logger.warning(f"Failed to parse {env_key}={value}")++ # Also check for any INGEST_ prefixed variables+ env_prefix = "INGEST_"+ for key, value in os.environ.items():+ if key.startswith(env_prefix) and key not in env_mappings:+ config_key = key[len(env_prefix):].lower()+ # Try to convert to appropriate type+ if value.lower() in ('true', 'false'):+ self._configs[config_key] = value.lower() == 'true'+ elif value.isdigit():+ self._configs[config_key] = int(value)+ else:+ try:+ self._configs[config_key] = float(value)+ except ValueError:+ self._configs[config_key] = value++ def set(self, key: str, value: Any):+ """Set configuration value programmatically."""+ self._configs[key] = value++ def get(self, key: str, default: Any = None) -> Any:+ """Get configuration value with fallback chain: config -> env -> default."""+ # Check config first+ if key in self._configs:+ return self._configs[key]++ # Check environment variables+ env_key = f"INGEST_{key.upper()}"+ value = os.getenv(env_key)+ if value:+ try:+ # Try to convert to appropriate type+ if isinstance(default, int):+ return int(value)+ elif isinstance(default, float):+ return float(value)+ elif isinstance(default, bool):+ return value.lower() in ("true", "1", "yes", "on")+ return value+ except (ValueError, TypeError):+ pass++ return default++ def set_method_config(self, method: str, **config):+ """Set method-specific configuration."""+ self._method_configs[method] = config++ def get_method_config(self, method: str) -> Dict:+ """Get method-specific configuration."""+ return self._method_configs.get(method, {})++ def get_all(self) -> Dict[str, Any]:+ """Get all configuration."""+ return {+ "config": self._configs.copy(),+ "method_configs": self._method_configs.copy()+ }+++# Global config instance+ingest_config = IngestConfig()+diff --git a/semantica/ingest/ingest_usage.md b/semantica/ingest/ingest_usage.mdnew file mode 100644index 00000000..7772de7c--- /dev/null+++ b/semantica/ingest/ingest_usage.md@@ -0,0 +1,979 @@+# Ingest Module Usage Guide++This guide demonstrates how to use the ingest module for ingesting data from various sources including files, web content, feeds, streams, repositories, emails, and databases.++## Table of Contents++1. [Basic Usage](#basic-usage)+2. [File Ingestion](#file-ingestion)+3. [Web Ingestion](#web-ingestion)+4. [Feed Ingestion](#feed-ingestion)+5. [Stream Ingestion](#stream-ingestion)+6. [Repository Ingestion](#repository-ingestion)+7. [Email Ingestion](#email-ingestion)+8. [Database Ingestion](#database-ingestion)+9. [Unified Ingestion](#unified-ingestion)+10. [Using Methods](#using-methods)+11. [Using Registry](#using-registry)+12. [Configuration](#configuration)+13. [Advanced Examples](#advanced-examples)++## Basic Usage++### Using the Unified Ingestion Function++```python+from semantica.ingest import ingest++# Ingest a file (auto-detects source type)+result = ingest("document.pdf", source_type="file")++# Ingest from web URL+result = ingest("https://example.com", source_type="web")++# Ingest from feed+result = ingest("https://example.com/feed.xml", source_type="feed")+```++### Using Main Classes++```python+from semantica.ingest import FileIngestor, WebIngestor++# Create ingestor+file_ingestor = FileIngestor()+web_ingestor = WebIngestor(delay=1.0, respect_robots=True)++# Ingest files+files = file_ingestor.ingest_directory("./documents", recursive=True)++# Ingest web content+content = web_ingestor.ingest_url("https://example.com")+```++## File Ingestion++### Single File Ingestion++```python+from semantica.ingest import ingest_file, FileIngestor++# Using convenience function+file_obj = ingest_file("document.pdf", method="file")++# Using class directly+ingestor = FileIngestor()+file_obj = ingestor.ingest_file("document.pdf", read_content=True)++print(f"File: {file_obj.name}")+print(f"Type: {file_obj.file_type}")+print(f"Size: {file_obj.size} bytes")+```++### Directory Ingestion++```python+from semantica.ingest import ingest_file++# Ingest directory recursively+files = ingest_file("./documents", method="directory", recursive=True)++# Ingest directory with filters+files = ingest_file(+ "./documents",+ method="directory",+ recursive=True,+ file_extensions=[".pdf", ".docx", ".txt"]+)++print(f"Ingested {len(files)} files")+```++### Cloud Storage Ingestion++```python+from semantica.ingest import ingest_file, FileIngestor+from semantica.ingest.file_ingestor import CloudStorageIngestor++# AWS S3 ingestion+s3_config = {+ "provider": "s3",+ "access_key_id": "your_key",+ "secret_access_key": "your_secret",+ "region": "us-east-1"+}++files = ingest_file("s3://bucket-name/path/", method="cloud", **s3_config)++# Google Cloud Storage ingestion+gcs_config = {+ "provider": "gcs",+ "credentials_path": "/path/to/credentials.json"+}++files = ingest_file("gs://bucket-name/path/", method="cloud", **gcs_config)++# Azure Blob Storage ingestion+azure_config = {+ "provider": "azure",+ "connection_string": "your_connection_string"+}++files = ingest_file("https://account.blob.core.windows.net/container/", method="cloud", **azure_config)+```++### File Type Detection++```python+from semantica.ingest import FileTypeDetector++detector = FileTypeDetector()++# Detect by extension+file_type = detector.detect_type("document.pdf")++# Detect by MIME type+file_type = detector.detect_type("document.pdf")++# Detect by magic numbers+with open("document.pdf", "rb") as f:+ content = f.read(1024)+ file_type = detector.detect_type("document.pdf", content=content)+```++## Web Ingestion++### Single URL Ingestion++```python+from semantica.ingest import ingest_web, WebIngestor++# Using convenience function+content = ingest_web("https://example.com", method="url")++# Using class directly+ingestor = WebIngestor(delay=1.0, respect_robots=True)+content = ingestor.ingest_url("https://example.com")++print(f"Title: {content.title}")+print(f"Text length: {len(content.text)}")+print(f"Links: {len(content.links)}")+```++### Sitemap Crawling++```python+from semantica.ingest import ingest_web++# Crawl sitemap+pages = ingest_web("https://example.com/sitemap.xml", method="sitemap")++print(f"Found {len(pages)} pages from sitemap")+for page in pages:+ print(f" - {page.url}")+```++### Domain Crawling++```python+from semantica.ingest import ingest_web++# Crawl domain+pages = ingest_web(+ "https://example.com",+ method="crawl",+ max_pages=100,+ respect_robots=True,+ delay=1.0+)++print(f"Crawled {len(pages)} pages")+```++### Rate Limiting and Robots.txt++```python+from semantica.ingest import WebIngestor++# Create ingestor with rate limiting and robots.txt compliance+ingestor = WebIngestor(+ delay=2.0, # 2 second delay between requests+ respect_robots=True, # Check robots.txt+ user_agent="MyBot/1.0"+)++content = ingestor.ingest_url("https://example.com")+```++### Content Extraction++```python+from semantica.ingest import ContentExtractor++extractor = ContentExtractor()++# Extract text from HTML+html = "<html><body><p>Hello World</p></body></html>"+text = extractor.extract_text(html)++# Extract metadata+metadata = extractor.extract_metadata(html, url="https://example.com")++# Extract links+links = extractor.extract_links(html, base_url="https://example.com")+```++## Feed Ingestion++### RSS Feed Ingestion++```python+from semantica.ingest import ingest_feed, FeedIngestor++# Using convenience function+feed = ingest_feed("https://example.com/feed.xml", method="rss")++# Using class directly+ingestor = FeedIngestor()+feed = ingestor.ingest_feed("https://example.com/feed.xml")++print(f"Feed: {feed.title}")+print(f"Items: {len(feed.items)}")+for item in feed.items:+ print(f" - {item.title}: {item.link}")+```++### Atom Feed Ingestion++```python+from semantica.ingest import ingest_feed++# Atom feed ingestion+feed = ingest_feed("https://example.com/atom.xml", method="atom")++print(f"Feed: {feed.title}")+print(f"Updated: {feed.updated}")+```++### Feed Discovery++```python+from semantica.ingest import ingest_feed++# Discover feeds from website+feeds = ingest_feed("https://example.com", method="discover")++print(f"Found {len(feeds)} feeds")+for feed_url in feeds:+ print(f" - {feed_url}")+```++### Feed Monitoring++```python+from semantica.ingest import FeedMonitor++def on_update(feed_data):+ print(f"Feed updated: {feed_data.title}")+ print(f"New items: {len(feed_data.items)}")++monitor = FeedMonitor(+ feed_url="https://example.com/feed.xml",+ check_interval=300, # Check every 5 minutes+ on_update=on_update+)++monitor.start()+```++## Stream Ingestion++### Kafka Stream Ingestion++```python+from semantica.ingest import ingest_stream++# Kafka stream ingestion+kafka_config = {+ "topic": "my-topic",+ "bootstrap_servers": ["localhost:9092"]+}++processor = ingest_stream(kafka_config, method="kafka")++# Set message handler+def handle_message(message):+ print(f"Received: {message.content}")++processor.set_message_handler(handle_message)+processor.start_consuming()+```++### RabbitMQ Stream Ingestion++```python+from semantica.ingest import ingest_stream++# RabbitMQ stream ingestion+rabbitmq_config = {+ "queue": "my-queue",+ "host": "localhost",+ "port": 5672,+ "username": "guest",+ "password": "guest"+}++processor = ingest_stream(rabbitmq_config, method="rabbitmq")++def handle_message(message):+ print(f"Received: {message.content}")++processor.set_message_handler(handle_message)+processor.start_consuming()+```++### AWS Kinesis Stream Ingestion++```python+from semantica.ingest import ingest_stream++# Kinesis stream ingestion+kinesis_config = {+ "stream_name": "my-stream",+ "region": "us-east-1"+}++processor = ingest_stream(kinesis_config, method="kinesis")++def handle_message(message):+ print(f"Received: {message.content}")++processor.set_message_handler(handle_message)+processor.start_consuming()+```++### Apache Pulsar Stream Ingestion++```python+from semantica.ingest import ingest_stream++# Pulsar stream ingestion+pulsar_config = {+ "topic": "my-topic",+ "service_url": "pulsar://localhost:6650"+}++processor = ingest_stream(pulsar_config, method="pulsar")++def handle_message(message):+ print(f"Received: {message.content}")++processor.set_message_handler(handle_message)+processor.start_consuming()+```++## Repository Ingestion++### Git Repository Ingestion++```python+from semantica.ingest import ingest_repository, RepoIngestor++# Clone and ingest repository+repo_data = ingest_repository(+ "https://github.com/user/repo.git",+ method="git"+)++print(f"Repository: {repo_data['name']}")+print(f"Files: {len(repo_data['files'])}")+print(f"Commits: {len(repo_data['commits'])}")+```++### Repository Analysis++```python+from semantica.ingest import ingest_repository++# Analyze existing repository+analysis = ingest_repository("./repo", method="analyze")++print(f"Languages: {analysis['languages']}")+print(f"Total lines: {analysis['total_lines']}")+print(f"Files: {len(analysis['files'])}")+```++### Commit Analysis++```python+from semantica.ingest import RepoIngestor++ingestor = RepoIngestor()++# Analyze commits+commits = ingestor.analyze_commits("./repo", max_commits=100)++for commit in commits:+ print(f"{commit.hash}: {commit.message}")+ print(f" Author: {commit.author}")+ print(f" Date: {commit.date}")+ print(f" Changes: +{commit.additions} -{commit.deletions}")+```++### Code Structure Analysis++```python+from semantica.ingest import CodeExtractor++extractor = CodeExtractor()++# Extract code structure+code_file = extractor.extract_code("./src/main.py")++print(f"Language: {code_file.language}")+print(f"Classes: {code_file.metadata.get('classes', [])}")+print(f"Functions: {code_file.metadata.get('functions', [])}")+```++## Email Ingestion++### IMAP Email Ingestion++```python+from semantica.ingest import ingest_email, EmailIngestor++# IMAP email ingestion+imap_config = {+ "host": "imap.example.com",+ "username": "[email protected]",+ "password": "password",+ "mailbox": "INBOX",+ "max_emails": 100+}++emails = ingest_email(imap_config, method="imap")++print(f"Retrieved {len(emails)} emails")+for email in emails:+ print(f" - {email.subject} from {email.from_address}")+```++### POP3 Email Ingestion++```python+from semantica.ingest import ingest_email++# POP3 email ingestion+pop3_config = {+ "host": "pop3.example.com",+ "username": "[email protected]",+ "password": "password",+ "max_emails": 100+}++emails = ingest_email(pop3_config, method="pop3")++print(f"Retrieved {len(emails)} emails")+```++### Email Thread Analysis++```python+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)++# Analyze threads+threads = ingestor.analyze_threads(emails)++print(f"Found {len(threads)} conversation threads")+for thread_id, thread_emails in threads.items():+ print(f" Thread {thread_id}: {len(thread_emails)} messages")+```++### Attachment Processing++```python+from semantica.ingest import AttachmentProcessor++processor = AttachmentProcessor()++# Process attachment+attachment_info = processor.process_attachment(+ attachment_data,+ filename="document.pdf",+ content_type="application/pdf"+)++print(f"Saved to: {attachment_info['saved_path']}")+print(f"Extracted text: {attachment_info.get('extracted_text', 'N/A')}")++# Cleanup+processor.cleanup_attachments([attachment_info['saved_path']])+```++## Database Ingestion++### PostgreSQL Ingestion++```python+from semantica.ingest import ingest_database, DBIngestor++# PostgreSQL ingestion+connection_string = "postgresql://user:password@localhost/dbname"++# Ingest entire database+data = ingest_database(connection_string)++# Ingest specific table+table_data = ingest_database(+ connection_string,+ table="users",+ limit=1000+)++print(f"Table: {table_data.table_name}")+print(f"Rows: {table_data.row_count}")+print(f"Columns: {[col['name'] for col in table_data.columns]}")+```++### MySQL Ingestion++```python+from semantica.ingest import ingest_database++# MySQL ingestion+connection_string = "mysql://user:password@localhost/dbname"++table_data = ingest_database(connection_string, table="users")+```++### SQLite Ingestion++```python+from semantica.ingest import ingest_database++# SQLite ingestion+connection_string = "sqlite:///database.db"++table_data = ingest_database(connection_string, table="users")+```++### Custom SQL Query++```python+from semantica.ingest import DBIngestor++ingestor = DBIngestor()++# Execute custom query+connection_string = "postgresql://user:password@localhost/dbname"+results = ingestor.execute_query(+ connection_string,+ "SELECT * FROM users WHERE age > ?",+ params=[18]+)++print(f"Retrieved {len(results)} rows")+```++### Schema Introspection++```python+from semantica.ingest import DatabaseConnector++connector = DatabaseConnector("postgresql")+engine = connector.connect("postgresql://user:password@localhost/dbname")++# Get schema information+schema = connector.get_schema(engine)++print(f"Tables: {schema['tables']}")+for table_name, columns in schema['columns'].items():+ print(f" {table_name}: {[col['name'] for col in columns]}")+```++## Unified Ingestion++### Auto-Detection++```python+from semantica.ingest import ingest++# Auto-detect source type from source+result = ingest("document.pdf") # Auto-detects file+result = ingest("https://example.com") # Auto-detects web+result = ingest("https://example.com/feed.xml") # Auto-detects feed+result = ingest("postgresql://user:pass@localhost/db") # Auto-detects database+```++### Explicit Source Type++```python+from semantica.ingest import ingest++# Explicit source type+result = ingest("document.pdf", source_type="file")+result = ingest("https://example.com", source_type="web")+result = ingest("https://example.com/feed.xml", source_type="feed")+```++### Batch Ingestion++```python+from semantica.ingest import ingest++# Ingest multiple sources+sources = [+ "document1.pdf",+ "document2.docx",+ "document3.txt"+]++result = ingest(sources, source_type="file")+print(f"Ingested {len(result['files'])} files")+```++## Using Methods++### Format-Specific Methods++```python+from semantica.ingest.methods import (+ ingest_file,+ ingest_web,+ ingest_feed,+ ingest_stream,+ ingest_repository,+ ingest_email,+ ingest_database+)++# File ingestion+files = ingest_file("./documents", method="directory")++# Web ingestion+content = ingest_web("https://example.com", method="url")++# Feed ingestion+feed = ingest_feed("https://example.com/feed.xml", method="rss")++# Stream ingestion+processor = ingest_stream({"topic": "my-topic", "bootstrap_servers": ["localhost:9092"]}, method="kafka")++# Repository ingestion+repo_data = ingest_repository("https://github.com/user/repo.git", method="git")++# Email ingestion+emails = ingest_email({"host": "imap.example.com", "username": "user", "password": "pass"}, method="imap")++# Database ingestion+data = ingest_database("postgresql://user:pass@localhost/db", table="users")+```++## Using Registry++### Registering Custom Methods++```python+from semantica.ingest.registry import method_registry++def custom_file_ingestion(source, **kwargs):+ """Custom file ingestion function."""+ # Your custom implementation+ pass++# Register custom method+method_registry.register("file", "custom_method", custom_file_ingestion)++# Use custom method+from semantica.ingest.methods import ingest_file+files = ingest_file("document.pdf", method="custom_method")+```++### Listing Available Methods++```python+from semantica.ingest.methods import list_available_methods++# List all methods+all_methods = list_available_methods()+print(all_methods)++# List methods for specific task+file_methods = list_available_methods("file")+print(file_methods)+```++### Getting Registered Methods++```python+from semantica.ingest.methods import get_ingest_method++# Get method from registry+method = get_ingest_method("file", "custom_method")+if method:+ result = method("document.pdf")+```++## Configuration++### Environment Variables++```bash+# Set ingestion configuration via environment variables+export INGEST_DEFAULT_SOURCE_TYPE="file"+export INGEST_MAX_FILE_SIZE=10485760+export INGEST_RECURSIVE="true"+export INGEST_READ_CONTENT="true"+export INGEST_RATE_LIMIT_DELAY=1.0+export INGEST_RESPECT_ROBOTS="true"+export INGEST_BATCH_SIZE=100+export INGEST_TIMEOUT=30.0+```++### Programmatic Configuration++```python+from semantica.ingest.config import ingest_config++# Set configuration+ingest_config.set("default_source_type", "file")+ingest_config.set("max_file_size", 10485760)+ingest_config.set("recursive", True)++# Get configuration+source_type = ingest_config.get("default_source_type", default="file")+max_size = ingest_config.get("max_file_size", default=10485760)++# Method-specific configuration+ingest_config.set_method_config("file", max_size=10485760, recursive=True)+file_config = ingest_config.get_method_config("file")+```++### Config File (YAML)++```yaml+ingest:+ default_source_type: "file"+ max_file_size: 10485760+ recursive: true+ read_content: true+ rate_limit_delay: 1.0+ respect_robots: true+ batch_size: 100+ timeout: 30.0++ingest_methods:+ file:+ max_size: 10485760+ recursive: true+ web:+ delay: 1.0+ respect_robots: true+ feed:+ timeout: 30.0+ stream:+ batch_size: 1000+```++```python+from semantica.ingest.config import IngestConfig++# Load from config file+config = IngestConfig(config_file="config.yaml")+```++## Advanced Examples++### Complete Ingestion Pipeline++```python+from semantica.ingest import ingest, ingest_file, ingest_web, ingest_feed++# Ingest from multiple sources+file_result = ingest_file("./documents", method="directory")+web_result = ingest_web("https://example.com", method="url")+feed_result = ingest_feed("https://example.com/feed.xml", method="rss")++# Process results+all_content = []+all_content.extend([f.content for f in file_result if hasattr(f, 'content')])+all_content.append(web_result.text)+all_content.extend([item.content for item in feed_result.items])+```++### Batch Processing with Progress Tracking++```python+from semantica.ingest import FileIngestor+from semantica.utils.progress_tracker import get_progress_tracker++ingestor = FileIngestor()+progress = get_progress_tracker()++# Ingest with progress tracking+files = ingestor.ingest_directory(+ "./documents",+ recursive=True,+ progress_callback=lambda current, total: progress.update(current, total)+)+```++### Error Handling++```python+from semantica.ingest import ingest+from semantica.utils.exceptions import ProcessingError++try:+ result = ingest("document.pdf", source_type="file")+except ProcessingError as e:+ print(f"Ingestion failed: {e}")+except Exception as e:+ print(f"Unexpected error: {e}")+```++### Custom Ingestion Method++```python+from semantica.ingest.registry import method_registry+from semantica.ingest.methods import ingest_file++def custom_pdf_ingestion(source, **kwargs):+ """Custom PDF ingestion with special processing."""+ from semantica.ingest import FileIngestor++ ingestor = FileIngestor()+ file_obj = ingestor.ingest_file(source, **kwargs)++ # Custom processing+ if file_obj.file_type == "pdf":+ # Add custom metadata+ file_obj.metadata["processed"] = True+ file_obj.metadata["custom_field"] = "custom_value"++ return file_obj++# Register custom method+method_registry.register("file", "custom_pdf", custom_pdf_ingestion)++# Use custom method+files = ingest_file("document.pdf", method="custom_pdf")+```++### Multi-Source Ingestion++```python+from semantica.ingest import ingest++# Ingest from multiple source types+sources = {+ "files": ["./documents"],+ "web": ["https://example.com"],+ "feeds": ["https://example.com/feed.xml"]+}++results = {}+for source_type, source_list in sources.items():+ for source in source_list:+ try:+ result = ingest(source, source_type=source_type)+ results[source] = result+ except Exception as e:+ print(f"Failed to ingest {source}: {e}")+```++## Best Practices++1. **Source Type Selection**: Choose the appropriate source type for your data+ - Files: Local filesystem or cloud storage+ - Web: URLs, sitemaps, domain crawling+ - Feeds: RSS, Atom feeds+ - Streams: Real-time data streams (Kafka, RabbitMQ, etc.)+ - Repositories: Git repositories+ - Emails: IMAP, POP3 email servers+ - Databases: SQL databases++2. **Rate Limiting**: Always use rate limiting for web ingestion+ ```python+ ingestor = WebIngestor(delay=1.0, respect_robots=True)+ ```++3. **Error Handling**: Always handle ingestion errors gracefully+ ```python+ try:+ result = ingest(source, source_type="file")+ except Exception as e:+ logger.error(f"Ingestion failed: {e}")+ ```++4. **Batch Processing**: Use batch processing for large datasets+ ```python+ ingestor = FileIngestor()+ files = ingestor.ingest_directory("./documents", batch_size=100)+ ```++5. **Progress Tracking**: Use progress tracking for long-running operations+ ```python+ from semantica.utils.progress_tracker import get_progress_tracker+ progress = get_progress_tracker()+ ```++6. **Configuration Management**: Use environment variables or config files for consistent settings+ ```python+ ingest_config.set("default_source_type", "file")+ ```++7. **Resource Cleanup**: Always cleanup resources after ingestion+ ```python+ processor = ingest_stream(config, method="kafka")+ try:+ processor.start_consuming()+ finally:+ processor.stop()+ ```++## Performance Tips++1. **Parallel Processing**: Use parallel processing for multiple sources+ ```python+ from concurrent.futures import ThreadPoolExecutor++ with ThreadPoolExecutor() as executor:+ executor.submit(ingest_file, "./documents1")+ executor.submit(ingest_file, "./documents2")+ ```++2. **Caching**: Cache ingested content when possible+ ```python+ # Check if already ingested+ if not Path("cache/document.pdf").exists():+ result = ingest_file("document.pdf")+ # Cache result+ ```++3. **Streaming**: Use streaming for large files or datasets+ ```python+ # Stream processing for large files+ processor = ingest_stream(config, method="kafka")+ processor.set_message_handler(process_message)+ ```++4. **Connection Pooling**: Reuse connections for database ingestion+ ```python+ connector = DatabaseConnector("postgresql")+ engine = connector.connect(connection_string)+ # Reuse engine for multiple queries+ ```++5. **Memory Management**: Process large datasets in batches+ ```python+ # Process in batches to avoid memory issues+ for batch in process_in_batches(large_dataset, batch_size=1000):+ result = ingest(batch)+ ```+diff --git a/semantica/ingest/methods.py b/semantica/ingest/methods.pynew file mode 100644index 00000000..c59c1493--- /dev/null+++ b/semantica/ingest/methods.py@@ -0,0 +1,755 @@+"""+Ingestion Methods Module++This module provides all ingestion methods as simple, reusable functions for+ingesting data from various sources including files, web, feeds, streams, repositories,+emails, and databases. It supports multiple ingestion approaches and integrates with+the method registry for extensibility.++Supported Methods:++File Ingestion:+ - "file": File ingestion from local filesystem+ - "directory": Directory ingestion with recursive scanning+ - "cloud": Cloud storage ingestion (S3, GCS, Azure)++Web Ingestion:+ - "url": Single URL ingestion+ - "sitemap": Sitemap-based crawling+ - "crawl": Domain crawling++Feed Ingestion:+ - "rss": RSS feed ingestion+ - "atom": Atom feed ingestion+ - "discover": Feed discovery from websites++Stream Ingestion:+ - "kafka": Kafka stream ingestion+ - "rabbitmq": RabbitMQ stream ingestion+ - "kinesis": AWS Kinesis stream ingestion+ - "pulsar": Apache Pulsar stream ingestion++Repository Ingestion:+ - "git": Git repository ingestion+ - "clone": Repository cloning+ - "analyze": Repository analysis++Email Ingestion:+ - "imap": IMAP email ingestion+ - "pop3": POP3 email ingestion++Database Ingestion:+ - "postgresql": PostgreSQL database ingestion+ - "mysql": MySQL database ingestion+ - "sqlite": SQLite database ingestion+ - "oracle": Oracle database ingestion+ - "mssql": SQL Server database ingestion++Algorithms Used:++File Ingestion:+ - File Type Detection: Multi-method detection (extension-based, MIME type, magic number analysis)+ - Directory Scanning: Recursive directory traversal with filtering+ - Cloud Storage Integration: AWS S3, Google Cloud Storage, Azure Blob Storage API integration+ - File Validation: Size limits, format validation, content verification+ - Batch Processing: Parallel file processing with progress tracking+ - Magic Number Analysis: Binary file signature detection for accurate type identification++Web Ingestion:+ - HTTP Request Handling: GET/POST requests with retry logic and error handling+ - Rate Limiting: Time-based delay enforcement between requests+ - Robots.txt Compliance: RobotFileParser-based robots.txt checking and URL filtering+ - Content Extraction: BeautifulSoup-based HTML parsing and text extraction+ - Sitemap Crawling: XML sitemap parsing and URL discovery+ - Link Discovery: HTML link extraction and domain filtering+ - JavaScript Rendering: Optional Selenium/Playwright integration for dynamic content+ - URL Normalization: URL parsing, joining, and canonicalization++Feed Ingestion:+ - RSS/Atom Parsing: XML parsing with format auto-detection+ - Feed Discovery: HTML link tag parsing for feed discovery+ - Date Parsing: Multiple date format parsing (RFC 822, ISO 8601, etc.)+ - Feed Validation: XML schema validation and format verification+ - Update Monitoring: Polling-based feed update detection with callbacks+ - Content Extraction: Feed item content and metadata extraction++Stream Ingestion:+ - Kafka Processing: Kafka consumer group management and message processing+ - RabbitMQ Processing: AMQP protocol handling and queue management+ - AWS Kinesis Processing: Kinesis stream reading and shard management+ - Apache Pulsar Processing: Pulsar consumer and subscription management+ - Message Transformation: Custom transformation pipeline for stream messages+ - Error Handling: Retry logic, dead letter queue handling, error recovery+ - Stream Monitoring: Health checks, metrics collection, performance monitoring+ - Partition Management: Partition assignment and load balancing++Repository Ingestion:+ - Git Operations: Repository cloning, branch checking, commit traversal+ - Code Extraction: File content extraction with language detection+ - Commit Analysis: Git log parsing, diff analysis, statistics calculation+ - Language Detection: File extension and content-based programming language identification+ - Code Structure Analysis: AST parsing for classes, functions, imports extraction+ - Dependency Analysis: Package manager file parsing (requirements.txt, package.json, etc.)+ - Documentation Extraction: README, docstring, and comment extraction++Email Ingestion:+ - IMAP Protocol: IMAP connection, mailbox selection, message retrieval+ - POP3 Protocol: POP3 connection and message downloading+ - Email Parsing: RFC 822 email message parsing with header and body extraction+ - Attachment Processing: MIME attachment extraction and file saving+ - Content Extraction: Plain text and HTML body extraction with BeautifulSoup+ - Thread Analysis: Message-ID and In-Reply-To header-based conversation threading+ - Link Extraction: URL extraction from email HTML content++Database Ingestion:+ - Database Connection: SQLAlchemy-based connection management with connection pooling+ - SQL Query Execution: Parameterized query execution with result set processing+ - Schema Introspection: Database schema analysis and table/column discovery+ - Data Type Conversion: Database-specific type to Python type conversion+ - Pagination: Large dataset processing with LIMIT/OFFSET or cursor-based pagination+ - Data Export: Result set to dictionary/JSON conversion+ - Multi-database Support: PostgreSQL, MySQL, SQLite, Oracle, SQL Server abstraction++Key Features:+ - Multiple ingestion source types+ - Unified ingestion function with source type dispatch+ - Method dispatchers with registry support+ - Custom method registration capability+ - Consistent interface across all methods++Main Functions:+ - ingest_file: File ingestion wrapper+ - ingest_web: Web ingestion wrapper+ - ingest_feed: Feed ingestion wrapper+ - ingest_stream: Stream ingestion wrapper+ - ingest_repository: Repository ingestion wrapper+ - ingest_email: Email ingestion wrapper+ - ingest_database: Database ingestion wrapper+ - ingest: Unified ingestion function with source type dispatch+ - get_ingest_method: Get ingestion method by name+ - list_available_methods: List registered methods++Example Usage:+ >>> from semantica.ingest.methods import ingest, ingest_file, ingest_web+ >>> # Unified ingestion+ >>> result = ingest("document.pdf", source_type="file")+ >>> # File ingestion+ >>> files = ingest_file("./documents", method="directory")+ >>> # Web ingestion+ >>> content = ingest_web("https://example.com", method="url")+"""++from typing import Any, Dict, List, Optional, Callable, Union+from pathlib import Path++from ..utils.logging import get_logger+from ..utils.exceptions import ProcessingError, ConfigurationError+from .file_ingestor import FileIngestor, FileObject+from .web_ingestor import WebIngestor, WebContent+from .feed_ingestor import FeedIngestor, FeedData+from .stream_ingestor import StreamIngestor, StreamProcessor+from .repo_ingestor import RepoIngestor+from .email_ingestor import EmailIngestor, EmailData+from .db_ingestor import DBIngestor, TableData+from .registry import method_registry+from .config import ingest_config++logger = get_logger("ingest_methods")+++def ingest_file(+ source: Union[str, Path, List[Union[str, Path]]],+ method: str = "file",+ **kwargs+) -> Union[FileObject, List[FileObject], Dict[str, Any]]:+ """+ Ingest files from source (convenience function).++ This is a user-friendly wrapper that ingests files using the specified method.++ Args:+ source: File path, directory path, or list of paths+ method: Ingestion method (default: "file")+ - "file": Single file ingestion+ - "directory": Directory ingestion with recursive scanning+ - "cloud": Cloud storage ingestion+ **kwargs: Additional options passed to FileIngestor++ Returns:+ FileObject, List[FileObject], or Dict with ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest_file+ >>> file_obj = ingest_file("document.pdf", method="file")+ >>> files = ingest_file("./documents", method="directory", recursive=True)+ """+ # Check for custom method in registry+ custom_method = method_registry.get("file", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("file")+ config.update(kwargs)++ ingestor = FileIngestor(**config)++ source_path = Path(source) if isinstance(source, (str, Path)) else None++ if method == "file" and source_path and source_path.is_file():+ return ingestor.ingest_file(source_path, **kwargs)+ elif method == "directory" or (source_path and source_path.is_dir()):+ recursive = kwargs.get("recursive", ingest_config.get("recursive", True))+ return ingestor.ingest_directory(source_path or source, recursive=recursive, **kwargs)+ elif method == "cloud":+ from .file_ingestor import CloudStorageIngestor+ provider = kwargs.get("provider", "s3")+ cloud_ingestor = CloudStorageIngestor(provider=provider, **config)+ return cloud_ingestor.ingest(source, **kwargs)+ else:+ # Default: try as file+ return ingestor.ingest_file(source, **kwargs)++ except Exception as e:+ logger.error(f"Failed to ingest file: {e}")+ raise+++def ingest_web(+ source: Union[str, List[str]],+ method: str = "url",+ **kwargs+) -> Union[WebContent, List[WebContent], Dict[str, Any]]:+ """+ Ingest web content from source (convenience function).++ This is a user-friendly wrapper that ingests web content using the specified method.++ Args:+ source: URL or list of URLs+ method: Ingestion method (default: "url")+ - "url": Single URL ingestion+ - "sitemap": Sitemap-based crawling+ - "crawl": Domain crawling+ **kwargs: Additional options passed to WebIngestor++ Returns:+ WebContent, List[WebContent], or Dict with ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest_web+ >>> content = ingest_web("https://example.com", method="url")+ >>> pages = ingest_web("https://example.com/sitemap.xml", method="sitemap")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("web", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("web")+ config.update(kwargs)++ ingestor = WebIngestor(**config)++ if method == "url":+ if isinstance(source, list):+ return [ingestor.ingest_url(url, **kwargs) for url in source]+ else:+ return ingestor.ingest_url(source, **kwargs)+ elif method == "sitemap":+ return ingestor.crawl_sitemap(source, **kwargs)+ elif method == "crawl":+ return ingestor.crawl_domain(source, **kwargs)+ else:+ # Default: try as URL+ return ingestor.ingest_url(source, **kwargs)++ except Exception as e:+ logger.error(f"Failed to ingest web: {e}")+ raise+++def ingest_feed(+ source: Union[str, List[str]],+ method: str = "rss",+ **kwargs+) -> Union[FeedData, List[FeedData], Dict[str, Any]]:+ """+ Ingest feeds from source (convenience function).++ This is a user-friendly wrapper that ingests feeds using the specified method.++ Args:+ source: Feed URL or list of feed URLs+ method: Ingestion method (default: "rss")+ - "rss": RSS feed ingestion+ - "atom": Atom feed ingestion+ - "discover": Feed discovery from websites+ **kwargs: Additional options passed to FeedIngestor++ Returns:+ FeedData, List[FeedData], or Dict with ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest_feed+ >>> feed = ingest_feed("https://example.com/feed.xml", method="rss")+ >>> feeds = ingest_feed("https://example.com", method="discover")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("feed", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("feed")+ config.update(kwargs)++ ingestor = FeedIngestor(**config)++ if method == "discover":+ return ingestor.discover_feeds(source, **kwargs)+ else:+ if isinstance(source, list):+ return [ingestor.ingest_feed(url, **kwargs) for url in source]+ else:+ return ingestor.ingest_feed(source, **kwargs)++ except Exception as e:+ logger.error(f"Failed to ingest feed: {e}")+ raise+++def ingest_stream(+ source: Dict[str, Any],+ method: str = "kafka",+ **kwargs+) -> StreamProcessor:+ """+ Ingest stream from source (convenience function).++ This is a user-friendly wrapper that ingests streams using the specified method.++ Args:+ source: Stream source configuration dictionary+ method: Ingestion method (default: "kafka")+ - "kafka": Kafka stream ingestion+ - "rabbitmq": RabbitMQ stream ingestion+ - "kinesis": AWS Kinesis stream ingestion+ - "pulsar": Apache Pulsar stream ingestion+ **kwargs: Additional options passed to StreamIngestor++ Returns:+ StreamProcessor instance++ Examples:+ >>> from semantica.ingest.methods import ingest_stream+ >>> processor = ingest_stream(+ ... {"topic": "my-topic", "bootstrap_servers": ["localhost:9092"]},+ ... method="kafka"+ ... )+ """+ # Check for custom method in registry+ custom_method = method_registry.get("stream", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("stream")+ config.update(kwargs)++ ingestor = StreamIngestor(**config)++ if method == "kafka":+ return ingestor.ingest_kafka(+ source.get("topic", ""),+ source.get("bootstrap_servers", []),+ **kwargs+ )+ elif method == "rabbitmq":+ return ingestor.ingest_rabbitmq(+ source.get("queue", ""),+ source.get("host", "localhost"),+ source.get("port", 5672),+ **kwargs+ )+ elif method == "kinesis":+ return ingestor.ingest_kinesis(+ source.get("stream_name", ""),+ source.get("region", "us-east-1"),+ **kwargs+ )+ elif method == "pulsar":+ return ingestor.ingest_pulsar(+ source.get("topic", ""),+ source.get("service_url", "pulsar://localhost:6650"),+ **kwargs+ )+ else:+ raise ProcessingError(f"Unknown stream method: {method}")++ except Exception as e:+ logger.error(f"Failed to ingest stream: {e}")+ raise+++def ingest_repository(+ source: Union[str, Path],+ method: str = "git",+ **kwargs+) -> Dict[str, Any]:+ """+ Ingest repository from source (convenience function).++ This is a user-friendly wrapper that ingests repositories using the specified method.++ Args:+ source: Repository URL or local path+ method: Ingestion method (default: "git")+ - "git": Git repository ingestion+ - "clone": Repository cloning+ - "analyze": Repository analysis+ **kwargs: Additional options passed to RepoIngestor++ Returns:+ Dict with repository ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest_repository+ >>> repo_data = ingest_repository("https://github.com/user/repo.git", method="git")+ >>> analysis = ingest_repository("./repo", method="analyze")+ """+ # Check for custom method in registry+ custom_method = method_registry.get("repo", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("repo")+ config.update(kwargs)++ ingestor = RepoIngestor(**config)++ if method == "clone" or (isinstance(source, str) and source.startswith(("http://", "https://", "git@"))):+ return ingestor.ingest_repository(source, **kwargs)+ elif method == "analyze":+ return ingestor.analyze_repository(source, **kwargs)+ else:+ # Default: ingest repository+ return ingestor.ingest_repository(source, **kwargs)++ except Exception as e:+ logger.error(f"Failed to ingest repository: {e}")+ raise+++def ingest_email(+ source: Dict[str, Any],+ method: str = "imap",+ **kwargs+) -> Union[EmailData, List[EmailData], Dict[str, Any]]:+ """+ Ingest emails from source (convenience function).++ This is a user-friendly wrapper that ingests emails using the specified method.++ Args:+ source: Email source configuration dictionary+ method: Ingestion method (default: "imap")+ - "imap": IMAP email ingestion+ - "pop3": POP3 email ingestion+ **kwargs: Additional options passed to EmailIngestor++ Returns:+ EmailData, List[EmailData], or Dict with ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest_email+ >>> emails = ingest_email(+ ... {"host": "imap.example.com", "username": "user", "password": "pass"},+ ... method="imap"+ ... )+ """+ # Check for custom method in registry+ custom_method = method_registry.get("email", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("email")+ config.update(kwargs)++ ingestor = EmailIngestor(**config)++ if method == "imap":+ ingestor.connect_imap(+ source.get("host", ""),+ username=source.get("username", ""),+ password=source.get("password", ""),+ **kwargs+ )+ mailbox = source.get("mailbox", "INBOX")+ max_emails = source.get("max_emails", 100)+ return ingestor.ingest_mailbox(mailbox, max_emails=max_emails, **kwargs)+ elif method == "pop3":+ ingestor.connect_pop3(+ source.get("host", ""),+ username=source.get("username", ""),+ password=source.get("password", ""),+ **kwargs+ )+ max_emails = source.get("max_emails", 100)+ return ingestor.ingest_pop3(max_emails=max_emails, **kwargs)+ else:+ raise ProcessingError(f"Unknown email method: {method}")++ except Exception as e:+ logger.error(f"Failed to ingest email: {e}")+ raise+++def ingest_database(+ source: Union[str, Dict[str, Any]],+ method: Optional[str] = None,+ **kwargs+) -> Union[TableData, List[TableData], Dict[str, Any]]:+ """+ Ingest database from source (convenience function).++ This is a user-friendly wrapper that ingests databases using the specified method.++ Args:+ source: Database connection string or configuration dictionary+ method: Ingestion method (auto-detected from connection string if None)+ - "postgresql": PostgreSQL database ingestion+ - "mysql": MySQL database ingestion+ - "sqlite": SQLite database ingestion+ - "oracle": Oracle database ingestion+ - "mssql": SQL Server database ingestion+ **kwargs: Additional options passed to DBIngestor++ Returns:+ TableData, List[TableData], or Dict with ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest_database+ >>> data = ingest_database("postgresql://user:pass@localhost/db", table="users")+ >>> tables = ingest_database("sqlite:///db.sqlite")+ """+ # Check for custom method in registry+ if method:+ custom_method = method_registry.get("db", method)+ if custom_method:+ try:+ return custom_method(source, **kwargs)+ except Exception as e:+ logger.warning(f"Custom method {method} failed: {e}, falling back to default")++ try:+ # Get config+ config = ingest_config.get_method_config("db")+ config.update(kwargs)++ ingestor = DBIngestor(**config)++ # Auto-detect database type from connection string+ if isinstance(source, str):+ if "postgresql" in source or "postgres" in source:+ method = "postgresql"+ elif "mysql" in source or "mariadb" in source:+ method = "mysql"+ elif "sqlite" in source:+ method = "sqlite"+ elif "oracle" in source:+ method = "oracle"+ elif "mssql" in source or "sqlserver" in source:+ method = "mssql"++ # Ingest database+ if "table" in kwargs:+ return ingestor.export_table(source, kwargs["table"], **{k: v for k, v in kwargs.items() if k != "table"})+ else:+ return ingestor.ingest_database(source, **kwargs)++ except Exception as e:+ logger.error(f"Failed to ingest database: {e}")+ raise+++def ingest(+ sources: Union[List[Union[str, Path]], str, Path],+ source_type: Optional[str] = None,+ method: Optional[str] = None,+ **kwargs+) -> Dict[str, Any]:+ """+ Ingest data from sources (unified convenience function).++ This is a user-friendly wrapper that automatically routes to the appropriate+ ingestor based on source type or auto-detection.++ Args:+ sources: Data source(s) - can be file paths, URLs, directories, etc.+ source_type: Source type (auto-detected if not specified)+ - "file": File ingestion+ - "web": Web ingestion+ - "feed": Feed ingestion+ - "stream": Stream ingestion+ - "repo": Repository ingestion+ - "email": Email ingestion+ - "db": Database ingestion+ method: Optional specific ingestion method+ **kwargs: Additional options passed to ingestor++ Returns:+ Dict with ingestion results++ Examples:+ >>> from semantica.ingest.methods import ingest+ >>> # File ingestion+ >>> result = ingest("document.pdf", source_type="file")+ >>> # Web ingestion+ >>> result = ingest("https://example.com", source_type="web")+ >>> # Auto-detect from source+ >>> result = ingest("https://example.com/feed.xml") # Auto-detects feed+ """+ # Auto-detect source type if not specified+ if not source_type:+ if isinstance(sources, (str, Path)):+ source_str = str(sources)+ if source_str.startswith(("http://", "https://")):+ # Check if it's a feed URL+ if any(ext in source_str for ext in [".xml", "/feed", "/rss", "/atom"]):+ source_type = "feed"+ else:+ source_type = "web"+ elif source_str.startswith(("postgresql://", "mysql://", "sqlite://", "oracle://", "mssql://")):+ source_type = "db"+ elif source_str.startswith(("git@", "https://github.com", "https://gitlab.com")):+ source_type = "repo"+ else:+ source_type = "file"+ else:+ source_type = "file"++ # Route to appropriate ingestor+ if source_type == "file":+ return {"files": ingest_file(sources, method=method or "file", **kwargs)}+ elif source_type == "web":+ return {"content": ingest_web(sources, method=method or "url", **kwargs)}+ elif source_type == "feed":+ return {"feeds": ingest_feed(sources, method=method or "rss", **kwargs)}+ elif source_type == "stream":+ if isinstance(sources, dict):+ return {"processor": ingest_stream(sources, method=method or "kafka", **kwargs)}+ else:+ raise ProcessingError("Stream ingestion requires configuration dictionary")+ elif source_type == "repo":+ return ingest_repository(sources, method=method or "git", **kwargs)+ elif source_type == "email":+ if isinstance(sources, dict):+ return {"emails": ingest_email(sources, method=method or "imap", **kwargs)}+ else:+ raise ProcessingError("Email ingestion requires configuration dictionary")+ elif source_type == "db":+ return {"data": ingest_database(sources, method=method, **kwargs)}+ else:+ raise ProcessingError(f"Unknown source type: {source_type}")+++def get_ingest_method(task: str, name: str) -> Optional[Callable]:+ """+ Get a registered ingestion method.++ Args:+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")+ name: Method name++ Returns:+ Registered method or None if not found++ Examples:+ >>> from semantica.ingest.methods import get_ingest_method+ >>> method = get_ingest_method("file", "custom_method")+ >>> if method:+ ... result = method("document.pdf")+ """+ return method_registry.get(task, name)+++def list_available_methods(task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all available ingestion methods.++ Args:+ task: Optional task type filter++ Returns:+ Dictionary mapping task types to method names++ Examples:+ >>> from semantica.ingest.methods import list_available_methods+ >>> all_methods = list_available_methods()+ >>> file_methods = list_available_methods("file")+ """+ return method_registry.list_all(task)+++# Register default methods+method_registry.register("file", "default", ingest_file)+method_registry.register("file", "file", ingest_file)+method_registry.register("file", "directory", ingest_file)+method_registry.register("file", "cloud", ingest_file)+method_registry.register("web", "default", ingest_web)+method_registry.register("web", "url", ingest_web)+method_registry.register("web", "sitemap", ingest_web)+method_registry.register("web", "crawl", ingest_web)+method_registry.register("feed", "default", ingest_feed)+method_registry.register("feed", "rss", ingest_feed)+method_registry.register("feed", "atom", ingest_feed)+method_registry.register("feed", "discover", ingest_feed)+method_registry.register("stream", "default", ingest_stream)+method_registry.register("stream", "kafka", ingest_stream)+method_registry.register("stream", "rabbitmq", ingest_stream)+method_registry.register("stream", "kinesis", ingest_stream)+method_registry.register("stream", "pulsar", ingest_stream)+method_registry.register("repo", "default", ingest_repository)+method_registry.register("repo", "git", ingest_repository)+method_registry.register("repo", "clone", ingest_repository)+method_registry.register("repo", "analyze", ingest_repository)+method_registry.register("email", "default", ingest_email)+method_registry.register("email", "imap", ingest_email)+method_registry.register("email", "pop3", ingest_email)+method_registry.register("db", "default", ingest_database)+method_registry.register("db", "postgresql", ingest_database)+method_registry.register("db", "mysql", ingest_database)+method_registry.register("db", "sqlite", ingest_database)+method_registry.register("db", "oracle", ingest_database)+method_registry.register("db", "mssql", ingest_database)+method_registry.register("ingest", "default", ingest)+method_registry.register("ingest", "unified", ingest)+diff --git a/semantica/ingest/registry.py b/semantica/ingest/registry.pynew file mode 100644index 00000000..4b94f347--- /dev/null+++ b/semantica/ingest/registry.py@@ -0,0 +1,134 @@+"""+Method Registry Module for Ingestion++This module provides a method registry system for registering custom ingestion methods,+enabling extensibility and community contributions to the ingestion toolkit.++Supported Registration Types:+ - Method Registry: Register custom ingestion methods for:+ * "file": File ingestion methods+ * "web": Web ingestion methods+ * "feed": Feed ingestion methods+ * "stream": Stream ingestion methods+ * "repo": Repository ingestion methods+ * "email": Email ingestion methods+ * "db": Database ingestion methods+ * "ingest": General ingestion methods++Algorithms Used:+ - Registry Pattern: Dictionary-based registration and lookup+ - Dynamic Registration: Runtime function registration+ - Type Checking: Type validation for registered components+ - Lookup Algorithms: Hash-based O(1) lookup for methods+ - Task-based Organization: Hierarchical organization by task type++Key Features:+ - Method registry for custom ingestion methods+ - Task-based method organization (file, web, feed, stream, repo, email, db, ingest)+ - Dynamic registration and unregistration+ - Easy discovery of available methods+ - Support for community-contributed extensions++Main Classes:+ - MethodRegistry: Registry for custom ingestion methods++Global Instances:+ - method_registry: Global method registry instance++Example Usage:+ >>> from semantica.ingest.registry import method_registry+ >>> method_registry.register("file", "custom_method", custom_file_ingestion_function)+ >>> available = method_registry.list_all("file")+"""++from typing import Dict, Callable, Any, List, Optional+++class MethodRegistry:+ """Registry for custom ingestion methods."""++ _methods: Dict[str, Dict[str, Callable]] = {+ "file": {},+ "web": {},+ "feed": {},+ "stream": {},+ "repo": {},+ "email": {},+ "db": {},+ "ingest": {},+ }++ @classmethod+ def register(cls, task: str, name: str, method_func: Callable):+ """+ Register a custom ingestion method.++ Args:+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")+ name: Method name+ method_func: Method function+ """+ if task not in cls._methods:+ cls._methods[task] = {}+ cls._methods[task][name] = method_func++ @classmethod+ def get(cls, task: str, name: str) -> Optional[Callable]:+ """+ Get method by task and name.++ Args:+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")+ name: Method name++ Returns:+ Method function or None+ """+ return cls._methods.get(task, {}).get(name)++ @classmethod+ def list_all(cls, task: Optional[str] = None) -> Dict[str, List[str]]:+ """+ List all registered methods.++ Args:+ task: Optional task type to filter by++ Returns:+ Dictionary mapping task types to method names+ """+ if task:+ return {task: list(cls._methods.get(task, {}).keys())}+ return {t: list(m.keys()) for t, m in cls._methods.items()}++ @classmethod+ def unregister(cls, task: str, name: str):+ """+ Unregister a method.++ Args:+ task: Task type ("file", "web", "feed", "stream", "repo", "email", "db", "ingest")+ name: Method name+ """+ if task in cls._methods and name in cls._methods[task]:+ del cls._methods[task][name]++ @classmethod+ def clear(cls, task: Optional[str] = None):+ """+ Clear all registered methods for a task or all tasks.++ Args:+ task: Optional task type to clear (clears all if None)+ """+ if task:+ if task in cls._methods:+ cls._methods[task].clear()+ else:+ for task_dict in cls._methods.values():+ task_dict.clear()+++# Global registry+method_registry = MethodRegistry()+