Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Implement all ingest module files

KaifAhmad1c7ef2b6f929a
diff --git a/development-roadmap.md b/development-roadmap.md
deleted file mode 100644
index a63939ab..00000000
--- a/development-roadmap.md
+++ /dev/null
@@ -1,868 +0,0 @@
-# Semantica Framework Development Plan
-
-## Overview
-
-Build a production-ready Python framework for transforming unstructured data into semantic layers, knowledge graphs, and embeddings. Follow SDK best practices with clean architecture, comprehensive testing, and extensive documentation.
-
-## Detailed Project Structure
-
-```
-semantica-3/
-├── libs/ # Core framework implementation
-│ ├── semantica/ # Main package
-│ │ ├── __init__.py
-│ │ │
-│ │ ├── core/ # Core orchestration
-│ │ │ ├── __init__.py
-│ │ │ ├── orchestrator.py
-│ │ │ ├── config_manager.py
-│ │ │ ├── plugin_registry.py
-│ │ │ └── lifecycle.py
-│ │ │
-│ │ ├── ingest/ # Data ingestion modules
-│ │ │ ├── __init__.py
-│ │ │ ├── file_ingestor.py
-│ │ │ ├── web_ingestor.py
-│ │ │ ├── feed_ingestor.py
-│ │ │ ├── stream_ingestor.py
-│ │ │ ├── repo_ingestor.py
-│ │ │ ├── email_ingestor.py
-│ │ │ └── db_ingestor.py
-│ │ │
-│ │ ├── parse/ # Format parsers
-│ │ │ ├── __init__.py
-│ │ │ ├── pdf_parser.py
-│ │ │ ├── docx_parser.py
-│ │ │ ├── pptx_parser.py
-│ │ │ ├── excel_parser.py
-│ │ │ ├── html_parser.py
-│ │ │ ├── csv_parser.py
-│ │ │ ├── json_parser.py
-│ │ │ ├── xml_parser.py
-│ │ │ ├── image_parser.py
-│ │ │ ├── latex_parser.py
-│ │ │ ├── epub_parser.py
-│ │ │ └── archive_parser.py
-│ │ │
-│ │ ├── normalize/ # Data normalization
-│ │ │ ├── __init__.py
-│ │ │ ├── text_cleaner.py
-│ │ │ ├── language_detector.py
-│ │ │ ├── encoding_handler.py
-│ │ │ ├── entity_normalizer.py
-│ │ │ ├── date_normalizer.py
-│ │ │ └── number_normalizer.py
-│ │ │
-│ │ ├── split/ # Chunking strategies
-│ │ │ ├── __init__.py
-│ │ │ ├── sliding_window_chunker.py
-│ │ │ ├── semantic_chunker.py
-│ │ │ ├── structural_chunker.py
-│ │ │ ├── table_chunker.py
-│ │ │ ├── provenance_tracker.py
-│ │ │ └── chunk_validator.py
-│ │ │
-│ │ ├── semantic_extract/ # NER, relations, triples
-│ │ │ ├── __init__.py
-│ │ │ ├── ner_extractor.py
-│ │ │ ├── relation_extractor.py
-│ │ │ ├── event_detector.py
-│ │ │ ├── coref_resolver.py
-│ │ │ ├── triple_extractor.py
-│ │ │ ├── llm_enhancer.py
-│ │ │ └── extraction_validator.py
-│ │ │
-│ │ ├── ontology/ # Ontology generation
-│ │ │ ├── __init__.py
-│ │ │ ├── class_inferrer.py
-│ │ │ ├── property_generator.py
-│ │ │ ├── owl_generator.py
-│ │ │ ├── schema_mapper.py
-│ │ │ ├── version_manager.py
-│ │ │ ├── ontology_validator.py
-│ │ │ └── domain_ontologies.py
-│ │ │
-│ │ ├── triple_store/ # Triple store adapters
-│ │ │ ├── __init__.py
-│ │ │ ├── blazegraph_adapter.py
-│ │ │ ├── jena_adapter.py
-│ │ │ ├── rdf4j_adapter.py
-│ │ │ ├── virtuoso_adapter.py
-│ │ │ ├── graphdb_adapter.py
-│ │ │ ├── triple_manager.py
-│ │ │ ├── query_engine.py
-│ │ │ └── bulk_loader.py
-│ │ │
-│ │ ├── kg/ # Knowledge graph
-│ │ │ ├── __init__.py
-│ │ │ ├── graph_builder.py
-│ │ │ ├── entity_resolver.py
-│ │ │ ├── deduplicator.py
-│ │ │ ├── seed_manager.py
-│ │ │ ├── provenance_tracker.py
-│ │ │ ├── conflict_detector.py
-│ │ │ ├── conflict_resolver.py
-│ │ │ ├── graph_validator.py
-│ │ │ ├── graph_analyzer.py
-│ │ │ ├── graph_metrics.py
-│ │ │ ├── centrality_calculator.py
-│ │ │ ├── community_detector.py
-│ │ │ ├── path_finder.py
-│ │ │ ├── graph_embedder.py
-│ │ │ ├── subgraph_extractor.py
-│ │ │ ├── anomaly_detector.py
-│ │ │ ├── temporal_graph.py
-│ │ │ └── graph_visualizer.py
-│ │ │
-│ │ ├── embeddings/ # Embedding generation
-│ │ │ ├── __init__.py
-│ │ │ ├── text_embedder.py
-│ │ │ ├── image_embedder.py
-│ │ │ ├── audio_embedder.py
-│ │ │ ├── multimodal_embedder.py
-│ │ │ ├── context_manager.py
-│ │ │ ├── pooling_strategies.py
-│ │ │ ├── provider_adapters.py
-│ │ │ └── embedding_optimizer.py
-│ │ │
-│ │ ├── vector_store/ # Vector DB adapters
-│ │ │ ├── __init__.py
-│ │ │ ├── pinecone_adapter.py
-│ │ │ ├── faiss_adapter.py
-│ │ │ ├── milvus_adapter.py
-│ │ │ ├── weaviate_adapter.py
-│ │ │ ├── qdrant_adapter.py
-│ │ │ ├── chroma_adapter.py
-│ │ │ ├── namespace_manager.py
-│ │ │ ├── metadata_store.py
-│ │ │ ├── hybrid_search.py
-│ │ │ └── index_optimizer.py
-│ │ │
-│ │ ├── reasoning/ # Inference engine
-│ │ │ ├── __init__.py
-│ │ │ ├── inference_engine.py
-│ │ │ ├── sparql_reasoner.py
-│ │ │ ├── rete_engine.py
-│ │ │ ├── abductive_reasoner.py
-│ │ │ ├── deductive_reasoner.py
-│ │ │ ├── rule_manager.py
-│ │ │ ├── reasoning_validator.py
-│ │ │ └── explanation_generator.py
-│ │ │
-│ │ ├── pipeline/ # Pipeline orchestration
-│ │ │ ├── __init__.py
-│ │ │ ├── pipeline_builder.py
-│ │ │ ├── execution_engine.py
-│ │ │ ├── failure_handler.py
-│ │ │ ├── parallelism_manager.py
-│ │ │ ├── resource_scheduler.py
-│ │ │ ├── pipeline_validator.py
-│ │ │ ├── monitoring_hooks.py
-│ │ │ └── pipeline_templates.py
-│ │ │
-│ │ ├── streaming/ # Real-time processing
-│ │ │ ├── __init__.py
-│ │ │ ├── kafka_adapter.py
-│ │ │ ├── pulsar_adapter.py
-│ │ │ ├── rabbitmq_adapter.py
-│ │ │ ├── kinesis_adapter.py
-│ │ │ ├── stream_processor.py
-│ │ │ ├── checkpoint_manager.py
-│ │ │ ├── exactly_once.py
-│ │ │ ├── backpressure_handler.py
-│ │ │ └── stream_monitor.py
-│ │ │
-│ │ ├── monitoring/ # Analytics & QA
-│ │ │ ├── __init__.py
-│ │ │ ├── analytics_dashboard.py
-│ │ │ ├── quality_assurance.py
-│ │ │ ├── performance_monitor.py
-│ │ │ ├── alert_manager.py
-│ │ │ ├── metrics_collector.py
-│ │ │ └── health_checker.py
-│ │ │
-│ │ ├── export/ # Export utilities
-│ │ │ ├── __init__.py
-│ │ │ ├── rdf_exporter.py
-│ │ │ ├── json_exporter.py
-│ │ │ ├── csv_exporter.py
-│ │ │ ├── graph_exporter.py
-│ │ │ └── report_generator.py
-│ │ │
-│ │ ├── security/ # Security & compliance
-│ │ │ ├── __init__.py
-│ │ │ ├── access_control.py
-│ │ │ ├── data_masking.py
-│ │ │ ├── pii_redactor.py
-│ │ │ ├── audit_logger.py
-│ │ │ ├── encryption_manager.py
-│ │ │ ├── security_validator.py
-│ │ │ ├── compliance_manager.py
-│ │ │ ├── threat_monitor.py
-│ │ │ └── vulnerability_scanner.py
-│ │ │
-│ │ ├── quality/ # Quality assurance
-│ │ │ ├── __init__.py
-│ │ │ ├── qa_engine.py
-│ │ │ ├── validation_engine.py
-│ │ │ ├── schema_validator.py
-│ │ │ ├── triple_validator.py
-│ │ │ ├── confidence_calculator.py
-│ │ │ ├── test_generator.py
-│ │ │ ├── quality_reporter.py
-│ │ │ ├── data_profiler.py
-│ │ │ └── compliance_checker.py
-│ │ │
-│ │ └── utils/ # Shared utilities
-│ │ ├── __init__.py
-│ │ ├── logging.py
-│ │ ├── exceptions.py
-│ │ ├── validators.py
-│ │ ├── helpers.py
-│ │ ├── constants.py
-│ │ └── types.py
-│ │
-│ ├── pyproject.toml # Package metadata (Poetry/PDM)
-│ ├── setup.py # Fallback setup
-│ ├── requirements.txt # Dependencies
-│ ├── requirements-dev.txt # Dev dependencies
-│ ├── README.md # Package README
-│ ├── LICENSE # MIT License
-│ └── tests/ # Test suite
-│ ├── __init__.py
-│ ├── conftest.py
-│ ├── unit/
-│ │ ├── __init__.py
-│ │ ├── test_core.py
-│ │ ├── test_ingest.py
-│ │ ├── test_parse.py
-│ │ ├── test_normalize.py
-│ │ ├── test_split.py
-│ │ ├── test_semantic_extract.py
-│ │ ├── test_ontology.py
-│ │ ├── test_triple_store.py
-│ │ ├── test_kg.py
-│ │ ├── test_embeddings.py
-│ │ ├── test_vector_store.py
-│ │ ├── test_reasoning.py
-│ │ ├── test_pipeline.py
-│ │ ├── test_streaming.py
-│ │ ├── test_monitoring.py
-│ │ ├── test_export.py
-│ │ └── test_utils.py
-│ ├── integration/
-│ │ ├── __init__.py
-│ │ ├── test_document_pipeline.py
-│ │ ├── test_kg_construction.py
-│ │ ├── test_semantic_search.py
-│ │ ├── test_streaming_pipeline.py
-│ │ └── test_end_to_end.py
-│ ├── fixtures/
-│ │ ├── __init__.py
-│ │ ├── sample_documents/
-│ │ │ ├── sample.pdf
-│ │ │ ├── sample.docx
-│ │ │ ├── sample.xlsx
-│ │ │ ├── sample.html
-│ │ │ └── sample.json
-│ │ ├── sample_configs/
-│ │ │ ├── pipeline_config.yaml
-│ │ │ └── ontology_config.yaml
-│ │ └── expected_outputs/
-│ │ ├── sample_triples.ttl
-│ │ └── sample_graph.json
-│ └── performance/
-│ ├── __init__.py
-│ ├── benchmark_parsing.py
-│ ├── benchmark_extraction.py
-│ └── benchmark_graph_ops.py
-│
-├── cookbook/ # Examples and use cases
-│ ├── README.md
-│ │
-│ ├── examples/ # Basic examples
-│ │ ├── 01_quick_start/
-│ │ │ ├── README.md
-│ │ │ ├── simple_processing.py
-│ │ │ ├── knowledge_graph_101.py
-│ │ │ └── semantic_search.py
-│ │ │
-│ │ ├── 02_document_processing/
-│ │ │ ├── README.md
-│ │ │ ├── pdf_extraction.py
-│ │ │ ├── office_documents.py
-│ │ │ ├── multi_format.py
-│ │ │ ├── web_scraping.py
-│ │ │ └── email_processing.py
-│ │ │
-│ │ ├── 03_knowledge_graphs/
-│ │ │ ├── README.md
-│ │ │ ├── building_kg.py
-│ │ │ ├── entity_resolution.py
-│ │ │ ├── conflict_detection.py
-│ │ │ ├── graph_analytics.py
-│ │ │ └── sparql_queries.py
-│ │ │
-│ │ ├── 04_semantic_search/
-│ │ │ ├── README.md
-│ │ │ ├── vector_search.py
-│ │ │ ├── hybrid_search.py
-│ │ │ ├── rag_pipeline.py
-│ │ │ └── semantic_ranking.py
-│ │ │
-│ │ └── 05_real_time_streams/
-│ │ ├── README.md
-│ │ ├── kafka_processing.py
-│ │ ├── feed_monitoring.py
-│ │ ├── web_monitoring.py
-│ │ └── event_driven_kg.py
-│ │
-│ ├── use_cases/ # Domain-specific examples
-│ │ ├── healthcare/
-│ │ │ ├── README.md
-│ │ │ ├── medical_literature.py
-│ │ │ ├── clinical_reports.py
-│ │ │ ├── drug_interactions.py
-│ │ │ └── patient_knowledge_graph.py
-│ │ │
-│ │ ├── finance/
-│ │ │ ├── README.md
-│ │ │ ├── financial_reports.py
-│ │ │ ├── market_intelligence.py
-│ │ │ ├── regulatory_compliance.py
-│ │ │ └── risk_analysis.py
-│ │ │
-│ │ ├── cybersecurity/
-│ │ │ ├── README.md
-│ │ │ ├── threat_intelligence.py
-│ │ │ ├── vulnerability_tracking.py
-│ │ │ ├── incident_analysis.py
-│ │ │ └── ioc_extraction.py
-│ │ │
-│ │ ├── research/
-│ │ │ ├── README.md
-│ │ │ ├── citation_network.py
-│ │ │ ├── research_trends.py
-│ │ │ ├── collaboration_graph.py
-│ │ │ └── paper_recommendation.py
-│ │ │
-│ │ └── legal/
-│ │ ├── README.md
-│ │ ├── case_law.py
-│ │ ├── contract_analysis.py
-│ │ ├── regulatory_mapping.py
-│ │ └── legal_entity_extraction.py
-│ │
-│ ├── notebooks/ # Jupyter notebooks
-│ │ ├── tutorials/
-│ │ │ ├── tutorial_01_getting_started.ipynb
-│ │ │ ├── tutorial_02_data_ingestion.ipynb
-│ │ │ ├── tutorial_03_semantic_extraction.ipynb
-│ │ │ ├── tutorial_04_knowledge_graphs.ipynb
-│ │ │ ├── tutorial_05_embeddings.ipynb
-│ │ │ └── tutorial_06_advanced_pipelines.ipynb
-│ │ │
-│ │ └── experiments/
-│ │ ├── experiment_custom_parsers.ipynb
-│ │ ├── experiment_reasoning.ipynb
-│ │ ├── experiment_optimization.ipynb
-│ │ └── experiment_multimodal.ipynb
-│ │
-│ └── data/ # Sample datasets
-│ ├── documents/
-│ │ ├── sample_papers.pdf
-│ │ ├── sample_reports.docx
-│ │ └── sample_data.csv
-│ ├── graphs/
-│ │ ├── sample_ontology.owl
-│ │ └── sample_triples.ttl
-│ └── configs/
-│ ├── pipeline_examples.yaml
-│ └── extraction_rules.json
-│
-├── docs/ # Documentation
-│ ├── index.md
-│ ├── getting-started.md
-│ ├── installation.md
-│ ├── architecture.md
-│ ├── api-reference/
-│ │ ├── index.md
-│ │ ├── core.md
-│ │ ├── ingest.md
-│ │ ├── parse.md
-│ │ ├── semantic_extract.md
-│ │ ├── ontology.md
-│ │ ├── kg.md
-│ │ ├── embeddings.md
-│ │ ├── vector_store.md
-│ │ ├── reasoning.md
-│ │ ├── pipeline.md
-│ │ └── streaming.md
-│ ├── tutorials/
-│ │ ├── quickstart.md
-│ │ ├── building-first-kg.md
-│ │ ├── semantic-search.md
-│ │ └── production-deployment.md
-│ ├── best-practices.md
-│ ├── performance-tuning.md
-│ ├── deployment.md
-│ └── contributing.md
-│
-├── .github/ # GitHub Actions CI/CD
-│ ├── workflows/
-│ │ ├── ci.yml
-│ │ ├── publish.yml
-│ │ └── docs.yml
-│ ├── ISSUE_TEMPLATE/
-│ │ ├── bug_report.md
-│ │ └── feature_request.md
-│ └── PULL_REQUEST_TEMPLATE.md
-│
-├── docker/ # Docker configurations
-│ ├── Dockerfile
-│ ├── docker-compose.yml
-│ ├── Dockerfile.dev
-│ └── .dockerignore
-│
-├── scripts/ # Utility scripts
-│ ├── setup_dev.sh
-│ ├── run_tests.sh
-│ ├── build_docs.sh
-│ ├── format_code.sh
-│ └── release.sh
-│
-├── README.md
-├── CONTRIBUTING.md
-├── LICENSE
-├── .gitignore
-├── .pre-commit-config.yaml
-└── mkdocs.yml
-```
-
-## Implementation Phases
-
-### Phase 1: Foundation & Core Architecture (Week 1-2)
-
-**1.1 Project Setup**
-
-- Create folder structure (libs/ and cookbook/)
-- Configure pyproject.toml with Poetry/PDM for dependency management
-- Setup development environment with pre-commit hooks
-- Configure pytest, black, flake8, mypy for code quality
-- Setup GitHub Actions CI/CD pipeline
-- Create basic README and CONTRIBUTING guidelines
-
-**1.2 Core Module (libs/semantica/core/)**
-
-- `orchestrator.py`: Main Semantica class, pipeline coordination
-- `config_manager.py`: YAML/JSON configuration handling
-- `plugin_registry.py`: Dynamic plugin loading system
-- `lifecycle.py`: Initialization, health checks, shutdown
-- Base classes and interfaces for all modules
-- Error handling and logging infrastructure
-
-**1.3 Utilities Module (libs/semantica/utils/)**
-
-- `logging.py`: Structured logging with levels and handlers
-- `exceptions.py`: Custom exception hierarchy
-- `validators.py`: Common validation functions
-- `helpers.py`: Shared utility functions
-- `constants.py`: Framework-wide constants
-- `types.py`: Type definitions and protocols
-
-### Phase 2: Data Ingestion & Parsing (Week 3-4)
-
-**2.1 Ingest Module (libs/semantica/ingest/)**
-
-- `file_ingestor.py`: Local file system, cloud storage (S3, GCS)
-- `web_ingestor.py`: HTTP scraping, sitemap crawling
-- `feed_ingestor.py`: RSS/Atom feed parsing
-- `stream_ingestor.py`: Real-time stream connections
-- `repo_ingestor.py`: Git repository processing
-- `email_ingestor.py`: Email protocol handlers
-- `db_ingestor.py`: Database export handling
-- `base_ingestor.py`: Abstract base class with common functionality
-
-**2.2 Parse Module (libs/semantica/parse/)**
-
-- `pdf_parser.py`: PDF text/table/image extraction (PyPDF2, pdfplumber)
-- `docx_parser.py`: Word document parsing (python-docx)
-- `pptx_parser.py`: PowerPoint parsing (python-pptx)
-- `excel_parser.py`: Excel parsing (openpyxl, pandas)
-- `html_parser.py`: HTML parsing (BeautifulSoup, lxml)
-- `csv_parser.py`: CSV/TSV parsing (pandas, csv)
-- `json_parser.py`: JSON/JSONL parsing
-- `xml_parser.py`: XML parsing (lxml, xmltodict)
-- `image_parser.py`: OCR and image analysis (Tesseract, PIL)
-- `base_parser.py`: Parser interface and registry
-
-### Phase 3: Normalization & Chunking (Week 5)
-
-**3.1 Normalize Module (libs/semantica/normalize/)**
-
-- `text_cleaner.py`: HTML removal, whitespace normalization
-- `language_detector.py`: Multi-language detection (langdetect)
-- `encoding_handler.py`: UTF-8 conversion, BOM handling
-- `entity_normalizer.py`: Entity standardization
-- `date_normalizer.py`: Date format standardization
-- `number_normalizer.py`: Number and unit normalization
-
-**3.2 Split Module (libs/semantica/split/)**
-
-- `sliding_window_chunker.py`: Fixed-size chunking with overlap
-- `semantic_chunker.py`: Meaning-based splitting (spaCy)
-- `structural_chunker.py`: Document-aware splitting
-- `table_chunker.py`: Table-aware chunking
-- `provenance_tracker.py`: Source tracking for chunks
-- `chunk_validator.py`: Chunk quality validation
-
-### Phase 4: Semantic Extraction (Week 6-7)
-
-**4.1 Semantic Extract Module (libs/semantica/semantic_extract/)**
-
-- `ner_extractor.py`: Named entity recognition (spaCy, transformers)
-- `relation_extractor.py`: Relationship detection
-- `event_detector.py`: Event identification
-- `coref_resolver.py`: Co-reference resolution
-- `triple_extractor.py`: RDF triple generation
-- `llm_enhancer.py`: LLM-based extraction (OpenAI, Anthropic)
-- `extraction_validator.py`: Quality validation
-
-**4.2 Ontology Module (libs/semantica/ontology/)**
-
-- `class_inferrer.py`: Automatic class discovery
-- `property_generator.py`: Property inference
-- `owl_generator.py`: OWL/RDF generation (rdflib)
-- `base_mapper.py`: Schema.org, FOAF, Dublin Core mapping
-- `version_manager.py`: Ontology versioning
-- `ontology_validator.py`: Schema validation
-- `domain_ontologies.py`: Pre-built domain ontologies
-
-### Phase 5: Knowledge Graph & Storage (Week 8-9)
-
-**5.1 Triple Store Module (libs/semantica/triple_store/)**
-
-- `base_adapter.py`: Abstract triple store interface
-- `blazegraph_adapter.py`: Blazegraph integration
-- `jena_adapter.py`: Apache Jena integration
-- `rdf4j_adapter.py`: RDF4J integration
-- `virtuoso_adapter.py`: Virtuoso integration
-- `triple_manager.py`: CRUD operations
-- `query_engine.py`: SPARQL query execution
-- `bulk_loader.py`: High-volume loading
-
-**5.2 KG Module (libs/semantica/kg/)**
-
-- `graph_builder.py`: Knowledge graph construction
-- `entity_resolver.py`: Entity disambiguation
-- `deduplicator.py`: Duplicate detection and merging
-- `seed_manager.py`: Initial data loading
-- `provenance_tracker.py`: Source tracking
-- `conflict_detector.py`: Conflict identification
-- `graph_validator.py`: Consistency validation
-- `graph_analyzer.py`: Analytics and metrics
-
-### Phase 6: Embeddings & Vector Storage (Week 10)
-
-**6.1 Embeddings Module (libs/semantica/embeddings/)**
-
-- `text_embedder.py`: Text embeddings (sentence-transformers)
-- `image_embedder.py`: Image embeddings (CLIP)
-- `audio_embedder.py`: Audio embeddings
-- `multimodal_embedder.py`: Cross-modal embeddings
-- `context_manager.py`: Context window management
-- `pooling_strategies.py`: Various pooling methods
-- `provider_adapters.py`: OpenAI, BGE, Llama adapters
-- `embedding_optimizer.py`: Optimization utilities
-
-**6.2 Vector Store Module (libs/semantica/vector_store/)**
-
-- `base_adapter.py`: Abstract vector store interface
-- `pinecone_adapter.py`: Pinecone integration
-- `faiss_adapter.py`: FAISS integration
-- `milvus_adapter.py`: Milvus integration
-- `weaviate_adapter.py`: Weaviate integration
-- `qdrant_adapter.py`: Qdrant integration
-- `namespace_manager.py`: Namespace isolation
-- `metadata_store.py`: Metadata indexing
-- `hybrid_search.py`: Vector + metadata search
-
-### Phase 7: Reasoning & Pipeline (Week 11)
-
-**7.1 Reasoning Module (libs/semantica/reasoning/)**
-
-- `inference_engine.py`: Rule-based inference
-- `sparql_reasoner.py`: SPARQL-based reasoning
-- `rete_engine.py`: Rete algorithm implementation
-- `abductive_reasoner.py`: Abductive reasoning
-- `deductive_reasoner.py`: Deductive reasoning
-- `rule_manager.py`: Rule management
-- `explanation_generator.py`: Explanation generation
-
-**7.2 Pipeline Module (libs/semantica/pipeline/)**
-
-- `pipeline_builder.py`: Pipeline construction DSL
-- `execution_engine.py`: Pipeline execution
-- `failure_handler.py`: Error handling and retry
-- `parallelism_manager.py`: Parallel execution
-- `resource_scheduler.py`: Resource allocation
-- `pipeline_validator.py`: Pipeline validation
-- `pipeline_templates.py`: Pre-built templates
-
-### Phase 8: Streaming & Real-time (Week 12)
-
-**8.1 Streaming Module (libs/semantica/streaming/)**
-
-- `kafka_adapter.py`: Apache Kafka integration
-- `pulsar_adapter.py`: Apache Pulsar integration
-- `rabbitmq_adapter.py`: RabbitMQ integration
-- `kinesis_adapter.py`: AWS Kinesis integration
-- `stream_processor.py`: Stream processing logic
-- `checkpoint_manager.py`: Checkpoint management
-- `exactly_once.py`: Exactly-once semantics
-- `backpressure_handler.py`: Flow control
-
-### Phase 9: Monitoring & Export (Week 13)
-
-**9.1 Monitoring Module (libs/semantica/monitoring/)**
-
-- `analytics_dashboard.py`: Real-time analytics
-- `quality_assurance.py`: Quality validation
-- `performance_monitor.py`: Performance tracking
-- `alert_manager.py`: Alert configuration
-- `metrics_collector.py`: Metrics collection
-- `health_checker.py`: Health monitoring
-
-**9.2 Export Module (libs/semantica/export/)**
-
-- `rdf_exporter.py`: RDF format exports
-- `json_exporter.py`: JSON/JSON-LD exports
-- `csv_exporter.py`: CSV exports
-- `graph_exporter.py`: Graph format exports
-- `report_generator.py`: Report generation
-
-### Phase 10: Examples & Documentation (Week 14-15)
-
-**10.1 Cookbook Examples (cookbook/examples/)**
-
-- **01_quick_start/**
- - `simple_processing.py`: Basic document processing
- - `knowledge_graph_101.py`: Simple KG construction
- - `semantic_search.py`: Basic semantic search
-
-- **02_document_processing/**
- - `pdf_extraction.py`: PDF processing pipeline
- - `office_documents.py`: DOCX/XLSX/PPTX processing
- - `multi_format.py`: Processing multiple formats
-
-- **03_knowledge_graphs/**
- - `building_kg.py`: Complete KG construction
- - `entity_resolution.py`: Entity disambiguation
- - `conflict_detection.py`: Handling conflicts
-
-- **04_semantic_search/**
- - `vector_search.py`: Vector similarity search
- - `hybrid_search.py`: Combined vector + metadata
- - `rag_pipeline.py`: RAG implementation
-
-- **05_real_time_streams/**
- - `kafka_processing.py`: Kafka stream processing
- - `feed_monitoring.py`: RSS feed monitoring
- - `web_monitoring.py`: Website change detection
-
-**10.2 Domain Use Cases (cookbook/use_cases/)**
-
-- **healthcare/**
- - `medical_literature.py`: PubMed processing
- - `clinical_reports.py`: Clinical report analysis
- - `drug_interactions.py`: Drug interaction detection
-
-- **finance/**
- - `financial_reports.py`: Financial document analysis
- - `market_intelligence.py`: News and market data
- - `regulatory_compliance.py`: Compliance monitoring
-
-- **cybersecurity/**
- - `threat_intelligence.py`: Threat report processing
- - `vulnerability_tracking.py`: CVE database integration
- - `incident_analysis.py`: Security incident analysis
-
-- **research/**
- - `citation_network.py`: Citation network building
- - `research_trends.py`: Trend analysis
- - `collaboration_graph.py`: Researcher networks
-
-- **legal/**
- - `case_law.py`: Legal case processing
- - `contract_analysis.py`: Contract intelligence
- - `regulatory_mapping.py`: Regulation tracking
-
-**10.3 Jupyter Notebooks (cookbook/notebooks/)**
-
-- `tutorial_01_getting_started.ipynb`: Introduction
-- `tutorial_02_data_ingestion.ipynb`: Data ingestion
-- `tutorial_03_semantic_extraction.ipynb`: Semantic extraction
-- `tutorial_04_knowledge_graphs.ipynb`: KG construction
-- `tutorial_05_embeddings.ipynb`: Embeddings and search
-- `tutorial_06_advanced_pipelines.ipynb`: Advanced pipelines
-- `experiment_custom_parsers.ipynb`: Custom parser development
-- `experiment_reasoning.ipynb`: Reasoning experiments
-
-**10.4 Documentation (docs/)**
-
-- `getting-started.md`: Quick start guide
-- `installation.md`: Installation instructions
-- `architecture.md`: System architecture
-- `api-reference/`: Complete API documentation
-- `tutorials/`: Step-by-step tutorials
-- `best-practices.md`: SDK best practices
-- `performance-tuning.md`: Optimization guide
-- `deployment.md`: Production deployment
-
-### Phase 11: Testing & Quality (Week 16)
-
-**11.1 Test Suite (libs/tests/)**
-
-- **unit/**: Unit tests for all modules (80%+ coverage)
-- **integration/**: Integration tests for workflows
-- **fixtures/**: Test data and mocks
-- **performance/**: Performance benchmarks
-- **e2e/**: End-to-end scenarios
-
-**11.2 Quality Assurance**
-
-- Comprehensive test coverage (target: 85%+)
-- Type hints throughout (mypy strict mode)
-- Code formatting (black, isort)
-- Linting (flake8, pylint)
-- Security scanning (bandit)
-- Documentation coverage (docstrings everywhere)
-
-### Phase 12: Packaging & Distribution (Week 17)
-
-**12.1 Package Configuration**
-
-- Configure pyproject.toml with proper metadata
-- Setup entry points for CLI tools
-- Configure optional dependencies ([all], [pdf], [web], etc.)
-- Build wheels and source distributions
-- Test installation in clean environments
-
-**12.2 Distribution**
-
-- PyPI package publishing
-- Docker image creation and DockerHub
-- Conda package (conda-forge)
-- GitHub releases with binaries
-- Documentation hosting (ReadTheDocs)
-
-### Phase 13: Final Polish (Week 18)
-
-**13.1 Documentation Review**
-
-- Complete API documentation
-- Tutorial walkthroughs
-- Example verification
-- FAQ and troubleshooting
-- Contributing guidelines
-
-**13.2 Community Setup**
-
-- GitHub repository setup
-- Issue templates
-- Pull request templates
-- Code of conduct
-- Community guidelines
-- Discord/Slack community
-
-## SDK Best Practices Applied
-
-1. **API-First Design**: Clear interfaces and protocols
-2. **Modular Architecture**: Pluggable components
-3. **Type Safety**: Full type hints throughout
-4. **Error Handling**: Specific exceptions with context
-5. **Documentation**: Comprehensive docstrings and guides
-6. **Testing**: High coverage with unit and integration tests
-7. **Versioning**: Semantic versioning (SemVer)
-8. **Backward Compatibility**: Deprecation warnings
-9. **Configuration**: Flexible, validated configuration
-10. **Observability**: Built-in logging and metrics
-11. **Performance**: Optimized with benchmarks
-12. **Security**: Input validation and secure defaults
-
-## Technology Stack
-
-**Core:**
-
-- Python 3.8+ (type hints, dataclasses, async/await)
-- Poetry/PDM for dependency management
-- pydantic for data validation
-- click for CLI
-
-**Data Processing:**
-
-- pandas, numpy for data manipulation
-- PyPDF2, pdfplumber for PDF
-- python-docx, python-pptx, openpyxl for Office
-- BeautifulSoup, lxml for HTML/XML
-- Pillow, pytesseract for images
-
-**NLP & Semantic:**
-
-- spaCy for NLP
-- transformers (HuggingFace) for models
-- sentence-transformers for embeddings
-- rdflib for RDF/OWL
-- nltk for text processing
-
-**Storage:**
-
-- Neo4j driver for graph DB
-- pinecone-client, faiss-cpu for vectors
-- requests for HTTP
-- SQLAlchemy for SQL databases
-
-**Streaming:**
-
-- kafka-python for Kafka
-- pika for RabbitMQ
-- redis for caching
-
-**Testing & Quality:**
-
-- pytest for testing
-- pytest-cov for coverage
-- black, isort for formatting
-- flake8, mypy for linting
-- pre-commit for hooks
-
-**Documentation:**
-
-- Sphinx for API docs
-- mkdocs-material for user docs
-- Jupyter for notebooks
-
-## Success Criteria
-
-1. ✅ Complete modular framework with 15+ modules
-2. ✅ Support for 20+ file formats
-3. ✅ 80%+ test coverage
-4. ✅ Comprehensive documentation
-5. ✅ 20+ working examples in cookbook
-6. ✅ 5+ domain-specific use cases
-7. ✅ PyPI package published
-8. ✅ Docker images available
-9. ✅ CI/CD pipeline functional
-10. ✅ Community resources setup
-
-## Milestones
-
-- **Week 2**: Core foundation and project structure
-- **Week 4**: Data ingestion and parsing complete
-- **Week 7**: Semantic extraction and ontology working
-- **Week 9**: Knowledge graph and storage functional
-- **Week 11**: Reasoning and pipelines operational
-- **Week 13**: Streaming and monitoring integrated
-- **Week 15**: Complete documentation and examples
-- **Week 17**: Package ready for distribution
-- **Week 18**: Launch ready with community support
diff --git a/libs/semantica/core/config_manager.py b/libs/semantica/core/config_manager.py
index 86bf1afd..f13e532c 100644
--- a/libs/semantica/core/config_manager.py
+++ b/libs/semantica/core/config_manager.py
@@ -20,11 +20,7 @@ import json
from pathlib import Path
from typing import Any, Dict, Optional, Union
-try:
- import yaml
- YAML_AVAILABLE = True
-except ImportError:
- YAML_AVAILABLE = False
+import yaml
from ..utils.exceptions import ConfigurationError
from ..utils.helpers import (
@@ -274,11 +270,6 @@ class ConfigManager:
try:
if suffix in (".yaml", ".yml"):
- if not YAML_AVAILABLE:
- raise ConfigurationError(
- "YAML support not available. Install PyYAML: pip install pyyaml"
- )
-
with open(file_path, "r", encoding="utf-8") as f:
config_dict = yaml.safe_load(f)
diff --git a/libs/semantica/ingest/db_ingestor.py b/libs/semantica/ingest/db_ingestor.py
index 24c7add0..9e9db43e 100644
--- a/libs/semantica/ingest/db_ingestor.py
+++ b/libs/semantica/ingest/db_ingestor.py
@@ -16,204 +16,563 @@ Main Classes:
- DataExporter: Data export processor
"""
+import json
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+from urllib.parse import urlparse
-class DBIngestor:
- """
- Database ingestion handler.
+import sqlalchemy
+from sqlalchemy import create_engine, inspect, text
+from sqlalchemy.engine import Engine
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class TableData:
+ """Table data representation."""
- • Connects to various database systems
- • Executes SQL queries and exports data
- • Handles different database schemas
- • Processes large datasets efficiently
- • Supports multiple database engines
- • Transforms data for semantic processing
+ table_name: str
+ columns: List[Dict[str, Any]]
+ rows: List[Dict[str, Any]]
+ row_count: int
+ schema: Optional[str] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+class DatabaseConnector:
+ """
+ Database connection management.
- 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
+ Manages connections to various databases,
+ handles connection pooling and reuse,
+ and provides unified interface for different DBs.
"""
- def __init__(self, config=None, **kwargs):
- """
- Initialize database ingestor.
-
- • Setup database connection parameters
- • Initialize database connectors
- • Configure data export settings
- • Setup schema analysis tools
- • Initialize supported database handlers
- """
- pass
+ SUPPORTED_DATABASES = {
+ 'postgresql': 'postgresql',
+ 'postgres': 'postgresql',
+ 'mysql': 'mysql+pymysql',
+ 'mariadb': 'mysql+pymysql',
+ 'sqlite': 'sqlite',
+ 'oracle': 'oracle',
+ 'mssql': 'mssql+pyodbc',
+ 'sqlserver': 'mssql+pyodbc',
+ }
- def ingest_database(self, connection_string, **options):
+ def __init__(self, db_type: str, **config):
"""
- Ingest data from entire database.
+ Initialize database connector.
- • Connect to database using connection string
- • Analyze database schema and structure
- • Identify tables and relationships
- • Export data from all tables
- • Process and transform data
- • Return database content collection
+ Args:
+ db_type: Database type (postgresql, mysql, sqlite, etc.)
+ **config: Connection configuration
"""
- pass
+ self.logger = get_logger("database_connector")
+ self.db_type = db_type.lower()
+ self.config = config
+ self.engine: Optional[Engine] = None
- def execute_query(self, connection_string, query, **params):
+ def connect(self, connection_string: str) -> Engine:
"""
- Execute SQL query and return results.
+ Establish database connection.
- • Connect to database
- • Execute SQL query with parameters
- • Process query results
- • Transform data to standard format
- • Handle errors and exceptions
- • Return query results
+ Args:
+ connection_string: Database connection string
+
+ Returns:
+ Engine: SQLAlchemy engine object
"""
- pass
+ try:
+ # Parse connection string to detect database type
+ parsed = urlparse(connection_string)
+
+ # Determine database type from connection string if not provided
+ if parsed.scheme:
+ db_type = parsed.scheme.split('+')[0]
+ if db_type in self.SUPPORTED_DATABASES:
+ self.db_type = db_type
+
+ # Get SQLAlchemy dialect
+ dialect = self.SUPPORTED_DATABASES.get(self.db_type, self.db_type)
+
+ # Create engine
+ self.engine = create_engine(connection_string, echo=False)
+
+ # Test connection
+ with self.engine.connect() as conn:
+ conn.execute(text("SELECT 1"))
+
+ self.logger.info(f"Connected to {self.db_type} 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}")
- def export_table(self, connection_string, table_name, **filters):
- """
- Export data from specific table.
-
- • Connect to database
- • Query table data with filters
- • Process table schema and metadata
- • Transform data for semantic processing
- • Handle large datasets with pagination
- • Return table data collection
- """
- pass
+ def disconnect(self):
+ """Close database connection."""
+ if self.engine:
+ self.engine.dispose()
+ self.engine = None
+ self.logger.info("Disconnected from database")
- def analyze_schema(self, connection_string):
+ def test_connection(self, connection_string: str) -> bool:
"""
- Analyze database schema and structure.
+ Test database connection.
- • Connect to database
- • Extract table and column information
- • Identify relationships and constraints
- • Analyze data types and patterns
- • Generate schema documentation
- • Return schema analysis results
+ Args:
+ connection_string: Database connection string
+
+ Returns:
+ bool: True if connection successful
"""
- pass
+ try:
+ engine = create_engine(connection_string)
+ with engine.connect() as conn:
+ conn.execute(text("SELECT 1"))
+ engine.dispose()
+ return True
+ except Exception:
+ return False
-class DatabaseConnector:
+class DataExporter:
"""
- Database connection management.
+ Database data export and transformation.
- • Manages connections to various databases
- • Handles connection pooling and reuse
- • Provides unified interface for different DBs
- • Manages authentication and security
+ Exports data from database tables,
+ transforms data to standard formats,
+ handles different data types,
+ and manages large dataset exports.
"""
- def __init__(self, db_type, **config):
+ def __init__(self, **config):
"""
- Initialize database connector.
+ Initialize data exporter.
- • Setup database-specific client
- • Configure connection parameters
- • Initialize connection pool
- • Setup authentication
+ Args:
+ **config: Exporter configuration
"""
- pass
+ self.logger = get_logger("data_exporter")
+ self.config = config
- def connect(self, connection_string):
+ def export_table_data(
+ self,
+ connection: Engine,
+ table_name: str,
+ schema: Optional[str] = None,
+ **options
+ ) -> TableData:
"""
- Establish database connection.
+ Export data from database table.
- • Parse connection string
- • Create database connection
- • Test connection validity
- • Setup connection options
- • Return connection object
+ 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
+
+ Returns:
+ TableData: Exported table data
"""
- pass
+ try:
+ inspector = inspect(connection)
+
+ # Get column information
+ columns = inspector.get_columns(table_name, schema=schema)
+ column_info = [
+ {
+ "name": col["name"],
+ "type": str(col["type"]),
+ "nullable": col.get("nullable", True),
+ "default": str(col.get("default")) if col.get("default") else None
+ }
+ for col in columns
+ ]
+
+ # Build query
+ query = f'SELECT * FROM {f"{schema}." if schema else ""}"{table_name}"'
+
+ if options.get("where"):
+ query += f" WHERE {options['where']}"
+
+ if options.get("order_by"):
+ query += f" ORDER BY {options['order_by']}"
+
+ if options.get("limit"):
+ query += f" LIMIT {options['limit']}"
+
+ if options.get("offset"):
+ query += f" OFFSET {options['offset']}"
+
+ # Execute query
+ with connection.connect() as conn:
+ result = conn.execute(text(query))
+ rows = []
+ for row in result:
+ row_dict = {}
+ for col_name, value in row._mapping.items():
+ # Convert datetime and other types to JSON-serializable format
+ if isinstance(value, datetime):
+ row_dict[col_name] = value.isoformat()
+ elif hasattr(value, '__dict__'):
+ row_dict[col_name] = str(value)
+ else:
+ row_dict[col_name] = value
+ rows.append(row_dict)
+
+ # Get 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']}"
+ count_result = conn.execute(text(count_query))
+ row_count = count_result.scalar()
+
+ return TableData(
+ table_name=table_name,
+ columns=column_info,
+ rows=rows,
+ row_count=row_count,
+ schema=schema
+ )
+
+ except Exception as e:
+ self.logger.error(f"Failed to export table {table_name}: {e}")
+ raise ProcessingError(f"Failed to export table: {e}")
- def disconnect(self, connection):
+ def transform_data(self, raw_data: List[Dict[str, Any]], schema_info: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
- Close database connection.
+ Transform raw database data.
- • Close active connection
- • Cleanup resources
- • Log connection closure
+ Args:
+ raw_data: Raw database rows
+ schema_info: Schema information
+
+ Returns:
+ list: Transformed data
"""
- pass
+ transformed = []
+
+ for row in raw_data:
+ transformed_row = {}
+ for col_name, value in row.items():
+ # Apply transformations
+ 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
+ else:
+ transformed_row[col_name] = value
+
+ transformed.append(transformed_row)
+
+ return transformed
- def test_connection(self, connection_string):
+ def export_schema(self, connection: Engine, schema: Optional[str] = None) -> Dict[str, Any]:
"""
- Test database connection.
+ Export database schema information.
- • Attempt to connect
- • Verify connection works
- • Check database accessibility
- • Return connection status
+ Args:
+ connection: Database connection engine
+ schema: Schema name (optional)
+
+ Returns:
+ dict: Schema information
"""
- pass
+ try:
+ inspector = inspect(connection)
+
+ schema_info = {
+ "tables": [],
+ "views": [],
+ "foreign_keys": []
+ }
+
+ # Get tables
+ tables = inspector.get_table_names(schema=schema)
+ for table_name in tables:
+ table_info = {
+ "name": table_name,
+ "columns": [],
+ "primary_keys": [],
+ "indexes": []
+ }
+
+ # Get columns
+ columns = inspector.get_columns(table_name, schema=schema)
+ for col in columns:
+ table_info["columns"].append({
+ "name": col["name"],
+ "type": str(col["type"]),
+ "nullable": col.get("nullable", True),
+ "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 indexes
+ indexes = inspector.get_indexes(table_name, schema=schema)
+ table_info["indexes"] = [idx["name"] for idx in indexes]
+
+ schema_info["tables"].append(table_info)
+
+ # Get views
+ try:
+ views = inspector.get_view_names(schema=schema)
+ schema_info["views"] = views
+ except Exception:
+ pass
+
+ # Get foreign keys
+ for table_name in tables:
+ try:
+ foreign_keys = inspector.get_foreign_keys(table_name, schema=schema)
+ schema_info["foreign_keys"].extend(foreign_keys)
+ except Exception:
+ pass
+
+ return schema_info
+
+ except Exception as e:
+ self.logger.error(f"Failed to export schema: {e}")
+ raise ProcessingError(f"Failed to export schema: {e}")
-class DataExporter:
+class DBIngestor:
"""
- Database data export and transformation.
+ Database ingestion handler.
+
+ Connects to various database systems,
+ executes SQL queries and exports data,
+ handles different database schemas,
+ and processes large datasets efficiently.
- • Exports data from database tables
- • Transforms data to standard formats
- • Handles different data types
- • Manages large dataset exports
+ 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
"""
- def __init__(self, **config):
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
- Initialize data exporter.
+ Initialize database ingestor.
- • Setup data transformation rules
- • Configure export formats
- • Initialize data type handlers
- • Setup pagination for large datasets
+ Args:
+ config: Database ingestion configuration
+ **kwargs: Additional configuration parameters
"""
- pass
+ self.logger = get_logger("db_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize connectors dictionary
+ self.connectors: Dict[str, DatabaseConnector] = {}
+
+ # Initialize exporter
+ self.exporter = DataExporter(**self.config)
+
+ # Supported databases
+ self.supported_databases = list(DatabaseConnector.SUPPORTED_DATABASES.keys())
- def export_table_data(self, connection, table_name, **options):
+ def ingest_database(self, connection_string: str, **options) -> Dict[str, Any]:
"""
- Export data from database table.
+ Ingest data from entire database.
- • Query table data
- • Apply filtering and sorting
- • Transform data types
- • Handle pagination for large tables
- • Return exported data collection
+ 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
+
+ Returns:
+ dict: Database content collection
"""
- pass
+ # Connect to database
+ connector = DatabaseConnector("", **self.config)
+ engine = connector.connect(connection_string)
+
+ try:
+ # Analyze schema
+ schema = self.analyze_schema(connection_string)
+
+ # Get 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", [])
+
+ if include_tables:
+ tables = [t for t in all_tables if t in include_tables]
+ else:
+ tables = [t for t in all_tables if t not in 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 {}
+ table_info = self.exporter.export_table_data(
+ engine,
+ table_name,
+ **table_options
+ )
+ 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
+ }
+ self.logger.debug(f"Exported table {table_name}: {table_info.row_count} rows")
+ except Exception as e:
+ self.logger.error(f"Failed to export table {table_name}: {e}")
+
+ return {
+ "schema": schema,
+ "tables": table_data,
+ "total_tables": len(tables),
+ "connection_string": connection_string
+ }
+
+ finally:
+ connector.disconnect()
- def transform_data(self, raw_data, schema_info):
+ def execute_query(self, connection_string: str, query: str, **params) -> List[Dict[str, Any]]:
"""
- Transform raw database data.
+ Execute SQL query and return results.
- • Apply data type conversions
- • Clean and normalize data
- • Handle null values and defaults
- • Format data for semantic processing
- • Return transformed data
+ Args:
+ connection_string: Database connection string
+ query: SQL query to execute
+ **params: Query parameters
+
+ Returns:
+ list: Query results
"""
- pass
+ connector = DatabaseConnector("", **self.config)
+ engine = connector.connect(connection_string)
+
+ try:
+ with engine.connect() as conn:
+ # Execute query with parameters
+ result = conn.execute(text(query), params)
+
+ # Convert results to list of dictionaries
+ rows = []
+ for row in result:
+ row_dict = {}
+ for col_name, value in row._mapping.items():
+ if isinstance(value, datetime):
+ row_dict[col_name] = value.isoformat()
+ elif hasattr(value, '__dict__'):
+ row_dict[col_name] = str(value)
+ else:
+ row_dict[col_name] = value
+ rows.append(row_dict)
+
+ return rows
+
+ except Exception as e:
+ self.logger.error(f"Failed to execute query: {e}")
+ raise ProcessingError(f"Failed to execute query: {e}")
+ finally:
+ connector.disconnect()
- def export_schema(self, connection):
+ def export_table(
+ self,
+ connection_string: str,
+ table_name: str,
+ schema: Optional[str] = None,
+ **filters
+ ) -> TableData:
"""
- Export database schema information.
+ Export data from specific table.
+
+ 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
+
+ Returns:
+ TableData: Table data collection
+ """
+ connector = DatabaseConnector("", **self.config)
+ engine = connector.connect(connection_string)
+
+ try:
+ table_data = self.exporter.export_table_data(
+ engine,
+ table_name,
+ schema=schema,
+ **filters
+ )
+
+ # Transform data if requested
+ if filters.get("transform", False):
+ schema_info = {"columns": table_data.columns}
+ table_data.rows = self.exporter.transform_data(table_data.rows, schema_info)
+
+ return table_data
+
+ finally:
+ connector.disconnect()
+
+ def analyze_schema(self, connection_string: str, schema: Optional[str] = None) -> Dict[str, Any]:
+ """
+ Analyze database schema and structure.
- • Extract table definitions
- • Get column information
- • Identify relationships
- • Generate schema metadata
- • Return schema information
+ Args:
+ connection_string: Database connection string
+ schema: Schema name (optional)
+
+ Returns:
+ dict: Schema analysis results
"""
- pass
+ connector = DatabaseConnector("", **self.config)
+ engine = connector.connect(connection_string)
+
+ try:
+ schema_info = self.exporter.export_schema(engine, schema=schema)
+
+ # 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"]
+ ))
+ }
+
+ return schema_info
+
+ finally:
+ connector.disconnect()
diff --git a/libs/semantica/ingest/email_ingestor.py b/libs/semantica/ingest/email_ingestor.py
index 29f93150..3f5b10a1 100644
--- a/libs/semantica/ingest/email_ingestor.py
+++ b/libs/semantica/ingest/email_ingestor.py
@@ -16,212 +16,619 @@ Main Classes:
- AttachmentProcessor: Email attachment handler
"""
+import email
+import imaplib
+import poplib
+import tempfile
+from dataclasses import dataclass, field
+from datetime import datetime
+from email.header import decode_header
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+from urllib.parse import urlparse
-class EmailIngestor:
- """
- Email protocol ingestion handler.
+from bs4 import BeautifulSoup
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class EmailData:
+ """Email data representation."""
- • Connects to email servers via IMAP/POP3
- • Retrieves emails from mailboxes
- • Processes email content and attachments
- • Extracts email metadata and headers
- • Handles email threading and conversations
- • Supports various email providers and protocols
+ message_id: str
+ subject: str
+ from_address: str
+ to_addresses: List[str]
+ cc_addresses: List[str] = field(default_factory=list)
+ date: Optional[datetime] = None
+ body_text: str = ""
+ body_html: str = ""
+ attachments: List[Dict[str, Any]] = field(default_factory=list)
+ headers: Dict[str, str] = field(default_factory=dict)
+ thread_id: Optional[str] = None
+
+
+class AttachmentProcessor:
+ """
+ Email attachment processing and extraction.
- 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
+ Processes various attachment types,
+ extracts text content from documents,
+ and handles image and media attachments.
"""
- def __init__(self, config=None, **kwargs):
+ def __init__(self, **config):
"""
- Initialize email ingestor.
+ Initialize attachment processor.
- • Setup email server connection parameters
- • Initialize IMAP and POP3 clients
- • Configure email parsing settings
- • Setup attachment processing
- • Initialize authentication handlers
+ Args:
+ **config: Processor configuration
"""
- pass
+ self.logger = get_logger("attachment_processor")
+ self.config = config
+ self.temp_dir = tempfile.mkdtemp(prefix="semantica_attachments_")
- def ingest_mailbox(self, mailbox_name="INBOX", **filters):
+ def process_attachment(self, attachment_data: bytes, filename: str, content_type: str) -> Dict[str, Any]:
"""
- Ingest emails from specified mailbox.
+ Process individual email attachment.
- • Connect to email server
- • Select specified mailbox
- • Search emails based on filters
- • Process each email individually
- • Extract content and metadata
- • Handle attachments if present
- • Return processed email collection
- """
- pass
-
- def process_email(self, email_data):
+ Args:
+ attachment_data: Attachment content bytes
+ filename: Attachment filename
+ content_type: MIME content type
+
+ Returns:
+ dict: Attachment information
"""
- Process individual email message.
+ attachment_info = {
+ "filename": filename,
+ "content_type": content_type,
+ "size": len(attachment_data),
+ "saved_path": None,
+ "text_content": None
+ }
- • Parse email headers and metadata
- • Extract sender, recipient, and subject
- • Process email body content
- • Handle HTML and plain text versions
- • Extract embedded images and links
- • Process email attachments
- • Return structured email data
- """
- pass
+ # Save attachment to temporary file
+ safe_filename = "".join(c for c in filename if c.isalnum() or c in ".-_")
+ file_path = Path(self.temp_dir) / safe_filename
+
+ try:
+ with open(file_path, 'wb') as f:
+ f.write(attachment_data)
+ attachment_info["saved_path"] = str(file_path)
+ except Exception as e:
+ self.logger.error(f"Failed to save attachment {filename}: {e}")
+ return attachment_info
+
+ # Extract text content if applicable
+ if content_type.startswith('text/'):
+ try:
+ text_content = attachment_data.decode('utf-8', errors='ignore')
+ attachment_info["text_content"] = text_content
+ except Exception:
+ pass
+ elif content_type in ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
+ # Extract text from documents
+ text_content = self.extract_text_content(file_path, content_type)
+ attachment_info["text_content"] = text_content
+
+ return attachment_info
- def extract_attachments(self, email_data):
+ def extract_text_content(self, attachment_path: Path, file_type: str) -> Optional[str]:
"""
- Extract and process email attachments.
+ Extract text content from attachment.
- • Identify attachment parts in email
- • Extract attachment content and metadata
- • Save attachments to temporary storage
- • Process different attachment types
- • Extract text content from documents
- • Return attachment information
+ Args:
+ attachment_path: Path to attachment file
+ file_type: File MIME type
+
+ Returns:
+ str: Extracted text content or None
"""
- pass
+ 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']:
+ # Word document extraction would require python-docx
+ return None # Placeholder - would need docx library
+ elif file_type.startswith('text/'):
+ with open(attachment_path, 'r', encoding='utf-8', errors='ignore') as f:
+ return f.read()
+ except Exception as e:
+ self.logger.error(f"Failed to extract text from {attachment_path}: {e}")
+
+ return None
- def analyze_threads(self, emails):
+ def cleanup_attachments(self, attachment_paths: List[str]):
"""
- Analyze email threads and conversations.
+ Clean up temporary attachment files.
- • Group emails by thread ID
- • Identify conversation participants
- • Analyze thread structure and flow
- • Extract conversation topics
- • Calculate thread metrics
- • Return thread analysis results
+ Args:
+ attachment_paths: List of attachment file paths
"""
- pass
+ import shutil
+ try:
+ if Path(self.temp_dir).exists():
+ shutil.rmtree(self.temp_dir)
+ except Exception as e:
+ self.logger.error(f"Failed to cleanup attachments: {e}")
class EmailParser:
"""
Email content parsing and extraction.
- • Parses email headers and metadata
- • Extracts email body content
- • Handles MIME multipart messages
- • Processes HTML and plain text content
- • Extracts embedded content and links
+ Parses email headers and metadata,
+ extracts email body content,
+ handles MIME multipart messages,
+ and processes HTML and plain text content.
"""
def __init__(self, **config):
"""
Initialize email parser.
- • Setup MIME message parser
- • Configure content extraction rules
- • Initialize HTML and text processors
- • Setup link and image extractors
+ Args:
+ **config: Parser configuration
"""
- pass
+ self.logger = get_logger("email_parser")
+ self.config = config
- def parse_headers(self, email_message):
+ def parse_headers(self, email_message: email.message.Message) -> Dict[str, str]:
"""
Parse email headers and metadata.
- • Extract standard email headers
- • Parse date and time information
- • Extract sender and recipient details
- • Process subject and message ID
- • Extract custom headers
- • Return header dictionary
+ Args:
+ email_message: Email message object
+
+ Returns:
+ dict: Header dictionary
"""
- pass
+ headers = {}
+
+ for header_name in email_message.keys():
+ header_value = email_message[header_name]
+ if header_value:
+ # Decode header if needed
+ decoded_value = decode_header(header_value)
+ decoded_str = ''.join(
+ part[0].decode(part[1] or 'utf-8') if isinstance(part[0], bytes) else part[0]
+ for part in decoded_value
+ )
+ headers[header_name.lower()] = decoded_str
+
+ return headers
- def parse_body(self, email_message):
+ def parse_body(self, email_message: email.message.Message) -> Dict[str, str]:
"""
Parse email body content.
- • Identify content type and encoding
- • Extract plain text content
- • Process HTML content if present
- • Handle multipart message structure
- • Extract embedded content
- • Return body content dictionary
+ Args:
+ email_message: Email message object
+
+ Returns:
+ dict: Body content dictionary with 'text' and 'html' keys
"""
- pass
+ body = {"text": "", "html": ""}
+
+ if email_message.is_multipart():
+ for part in email_message.walk():
+ content_type = part.get_content_type()
+ content_disposition = str(part.get("Content-Disposition", ""))
+
+ # Skip attachments
+ if "attachment" in content_disposition:
+ continue
+
+ # Extract text content
+ if content_type == "text/plain":
+ try:
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or 'utf-8'
+ body["text"] = payload.decode(charset, errors='ignore')
+ except Exception as e:
+ self.logger.warning(f"Failed to decode text part: {e}")
+
+ # Extract HTML content
+ elif content_type == "text/html":
+ try:
+ payload = part.get_payload(decode=True)
+ if payload:
+ charset = part.get_content_charset() or 'utf-8'
+ body["html"] = payload.decode(charset, errors='ignore')
+ except Exception as e:
+ self.logger.warning(f"Failed to decode HTML part: {e}")
+ else:
+ # Single part message
+ content_type = email_message.get_content_type()
+ try:
+ payload = email_message.get_payload(decode=True)
+ if payload:
+ charset = email_message.get_content_charset() or 'utf-8'
+ decoded = payload.decode(charset, errors='ignore')
+
+ if content_type == "text/html":
+ body["html"] = decoded
+ else:
+ body["text"] = decoded
+ except Exception as e:
+ self.logger.warning(f"Failed to decode body: {e}")
+
+ return body
- def extract_links(self, email_content):
+ def extract_links(self, email_content: str) -> List[str]:
"""
Extract links from email content.
- • Find URLs in text content
- • Extract links from HTML
- • Validate and normalize URLs
- • Categorize link types
- • Return link collection
+ Args:
+ email_content: Email content (HTML or text)
+
+ Returns:
+ list: List of extracted links
"""
- pass
+ links = []
+
+ # Extract from HTML if available
+ if email_content.strip().startswith('<'):
+ try:
+ soup = BeautifulSoup(email_content, 'html.parser')
+ for link_tag in soup.find_all('a', href=True):
+ links.append(link_tag['href'])
+ except Exception:
+ pass
+
+ # Extract URLs from text using regex
+ import re
+ url_pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
+ text_links = re.findall(url_pattern, email_content)
+ links.extend(text_links)
+
+ # Remove duplicates
+ return list(set(links))
-class AttachmentProcessor:
+class EmailIngestor:
"""
- Email attachment processing and extraction.
+ Email protocol ingestion handler.
+
+ Connects to email servers via IMAP/POP3,
+ retrieves emails from mailboxes,
+ and processes email content and attachments.
- • Processes various attachment types
- • Extracts text content from documents
- • Handles image and media attachments
- • Manages attachment storage and cleanup
+ 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
"""
- def __init__(self, **config):
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
- Initialize attachment processor.
+ Initialize email ingestor.
- • Setup file type handlers
- • Configure extraction tools
- • Initialize storage management
- • Setup cleanup procedures
+ Args:
+ config: Email ingestion configuration
+ **kwargs: Additional configuration parameters
"""
- pass
+ self.logger = get_logger("email_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize parser
+ self.parser = EmailParser(**self.config)
+
+ # Initialize attachment processor
+ self.attachment_processor = AttachmentProcessor(**self.config)
+
+ # Connection objects (initialized on connect)
+ self.imap_client: Optional[imaplib.IMAP4_SSL] = None
+ self.pop3_client: Optional[poplib.POP3_SSL] = None
- def process_attachment(self, attachment_data):
+ def connect_imap(self, server: str, port: int = 993, username: str = None, password: str = None):
"""
- Process individual email attachment.
+ Connect to IMAP server.
- • Identify attachment type and format
- • Extract attachment metadata
- • Save attachment to temporary storage
- • Extract text content if applicable
- • Process images and media files
- • Return attachment information
+ Args:
+ server: IMAP server address
+ port: IMAP server port (default: 993)
+ username: Email username
+ password: Email password
"""
- pass
+ 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}")
+ except Exception as e:
+ self.logger.error(f"Failed to connect to IMAP: {e}")
+ raise ProcessingError(f"Failed to connect to IMAP server: {e}")
- def extract_text_content(self, attachment_path, file_type):
+ def connect_pop3(self, server: str, port: int = 995, username: str = None, password: str = None):
"""
- Extract text content from attachment.
+ Connect to POP3 server.
- • Detect file type and format
- • Apply appropriate text extraction method
- • Handle various document formats
- • Extract metadata and structure
- • Return extracted text content
+ Args:
+ server: POP3 server address
+ port: POP3 server port (default: 995)
+ username: Email username
+ password: Email password
"""
- pass
+ 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}")
+ except Exception as e:
+ self.logger.error(f"Failed to connect to POP3: {e}")
+ raise ProcessingError(f"Failed to connect to POP3 server: {e}")
- def cleanup_attachments(self, attachment_paths):
+ def ingest_mailbox(self, mailbox_name: str = "INBOX", protocol: str = "imap", **filters) -> List[EmailData]:
"""
- Clean up temporary attachment files.
+ Ingest emails from specified mailbox.
+
+ 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
+
+ Returns:
+ list: Processed email collection
+ """
+ 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)
+ elif protocol.lower() == "pop3":
+ if not self.pop3_client:
+ raise ProcessingError("POP3 client not connected. Call connect_pop3() first.")
+ return self._ingest_pop3(**filters)
+ else:
+ raise ValidationError(f"Unsupported protocol: {protocol}")
+
+ def _ingest_imap(self, mailbox_name: str, **filters) -> List[EmailData]:
+ """Ingest emails using IMAP."""
+ try:
+ # Select mailbox
+ self.imap_client.select(mailbox_name)
+
+ # Build search criteria
+ search_criteria = "ALL"
+ if filters.get("unread_only"):
+ search_criteria = "UNSEEN"
+ if filters.get("since"):
+ search_criteria = f"({search_criteria} SINCE {filters['since']})"
+
+ # Search for emails
+ status, message_ids = self.imap_client.search(None, search_criteria)
+
+ if status != "OK":
+ raise ProcessingError("Failed to search emails")
+
+ email_ids = message_ids[0].split()
+
+ # Limit number of emails
+ max_emails = filters.get("max_emails")
+ if max_emails:
+ email_ids = email_ids[-max_emails:] # Get most recent
+
+ emails = []
+ for email_id in email_ids:
+ try:
+ status, msg_data = self.imap_client.fetch(email_id, '(RFC822)')
+ if status == "OK":
+ email_message = email.message_from_bytes(msg_data[0][1])
+ email_data = self.process_email(email_message)
+ emails.append(email_data)
+ except Exception as e:
+ self.logger.error(f"Failed to process email {email_id}: {e}")
+
+ return emails
+
+ except Exception as e:
+ self.logger.error(f"Error ingesting IMAP mailbox: {e}")
+ raise ProcessingError(f"Failed to ingest mailbox: {e}")
+
+ def _ingest_pop3(self, **filters) -> List[EmailData]:
+ """Ingest emails using POP3."""
+ try:
+ # Get email list
+ num_messages = len(self.pop3_client.list()[1])
+
+ max_emails = filters.get("max_emails", num_messages)
+ emails = []
+
+ # Fetch emails (most recent first)
+ start = max(1, num_messages - max_emails + 1)
+ for i in range(start, num_messages + 1):
+ try:
+ response = self.pop3_client.retr(i)
+ email_content = b'\n'.join(response[1])
+ email_message = email.message_from_bytes(email_content)
+ email_data = self.process_email(email_message)
+ emails.append(email_data)
+ except Exception as e:
+ self.logger.error(f"Failed to process email {i}: {e}")
+
+ return emails
+
+ except Exception as e:
+ 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:
+ """
+ Process individual email message.
+
+ Args:
+ email_message: Email message object
+
+ Returns:
+ EmailData: Structured email data
+ """
+ # Parse headers
+ headers = self.parser.parse_headers(email_message)
+
+ # Extract basic information
+ message_id = headers.get('message-id', '')
+ subject = headers.get('subject', '')
+ from_address = headers.get('from', '')
+ to_addresses = self._parse_address_list(headers.get('to', ''))
+ cc_addresses = self._parse_address_list(headers.get('cc', ''))
+
+ # Parse date
+ date_str = headers.get('date', '')
+ email_date = None
+ if date_str:
+ try:
+ from email.utils import parsedate_to_datetime
+ email_date = parsedate_to_datetime(date_str)
+ except Exception:
+ pass
- • Remove temporary files
- • Clear attachment storage
- • Free up disk space
- • Log cleanup activities
+ # Parse body
+ body = self.parser.parse_body(email_message)
+
+ # Extract thread ID
+ thread_id = headers.get('in-reply-to') or headers.get('references', '').split()[0] if headers.get('references') else None
+
+ # Extract attachments
+ attachments = self.extract_attachments(email_message)
+
+ return EmailData(
+ message_id=message_id,
+ subject=subject,
+ from_address=from_address,
+ to_addresses=to_addresses,
+ cc_addresses=cc_addresses,
+ date=email_date,
+ body_text=body["text"],
+ body_html=body["html"],
+ attachments=attachments,
+ headers=headers,
+ thread_id=thread_id
+ )
+
+ def extract_attachments(self, email_message: email.message.Message) -> List[Dict[str, Any]]:
+ """
+ Extract and process email attachments.
+
+ Args:
+ email_message: Email message object
+
+ Returns:
+ list: Attachment information
+ """
+ attachments = []
+
+ if email_message.is_multipart():
+ for part in email_message.walk():
+ content_disposition = str(part.get("Content-Disposition", ""))
+
+ if "attachment" in content_disposition:
+ filename = part.get_filename()
+ if filename:
+ # Decode filename
+ decoded_filename = decode_header(filename)[0][0]
+ if isinstance(decoded_filename, bytes):
+ decoded_filename = decoded_filename.decode('utf-8', errors='ignore')
+
+ # Get attachment data
+ attachment_data = part.get_payload(decode=True)
+ content_type = part.get_content_type()
+
+ # Process attachment
+ attachment_info = self.attachment_processor.process_attachment(
+ attachment_data,
+ decoded_filename,
+ content_type
+ )
+ attachments.append(attachment_info)
+
+ return attachments
+
+ def analyze_threads(self, emails: List[EmailData]) -> Dict[str, Any]:
"""
- pass
+ Analyze email threads and conversations.
+
+ Args:
+ emails: List of email data objects
+
+ Returns:
+ dict: Thread analysis results
+ """
+ threads = {}
+
+ for email_data in emails:
+ thread_id = email_data.thread_id or email_data.message_id
+
+ if thread_id not in threads:
+ threads[thread_id] = {
+ "thread_id": thread_id,
+ "emails": [],
+ "participants": set(),
+ "subject": email_data.subject,
+ "message_count": 0
+ }
+
+ threads[thread_id]["emails"].append(email_data)
+ threads[thread_id]["participants"].add(email_data.from_address)
+ threads[thread_id]["participants"].update(email_data.to_addresses)
+ threads[thread_id]["message_count"] += 1
+
+ # Convert sets to lists for JSON serialization
+ for thread in threads.values():
+ thread["participants"] = list(thread["participants"])
+
+ return {
+ "total_threads": len(threads),
+ "threads": list(threads.values())
+ }
+
+ def _parse_address_list(self, address_string: str) -> List[str]:
+ """Parse email address list string into list of addresses."""
+ if not address_string:
+ return []
+
+ addresses = []
+ try:
+ from email.utils import parseaddr, getaddresses
+ parsed_addresses = getaddresses([address_string])
+ addresses = [addr[1] for addr in parsed_addresses if addr[1]]
+ except Exception:
+ # Fallback: simple extraction
+ import re
+ email_pattern = r'[\w\.-]+@[\w\.-]+\.\w+'
+ addresses = re.findall(email_pattern, address_string)
+
+ return addresses
+
+ def disconnect(self):
+ """Disconnect from email servers."""
+ if self.imap_client:
+ try:
+ self.imap_client.close()
+ self.imap_client.logout()
+ except Exception:
+ pass
+ self.imap_client = None
+
+ if self.pop3_client:
+ try:
+ self.pop3_client.quit()
+ except Exception:
+ pass
+ self.pop3_client = None
diff --git a/libs/semantica/ingest/feed_ingestor.py b/libs/semantica/ingest/feed_ingestor.py
index ede2b9e8..fc5056aa 100644
--- a/libs/semantica/ingest/feed_ingestor.py
+++ b/libs/semantica/ingest/feed_ingestor.py
@@ -16,110 +16,48 @@ Main Classes:
- FeedMonitor: Feed update monitoring
"""
+import time
+import threading
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+from urllib.parse import urljoin, urlparse
-class FeedIngestor:
- """
- RSS/Atom feed ingestion handler.
-
- Processes 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
- """
-
- def __init__(self, config=None, **kwargs):
- """
- Initialize feed ingestor.
-
- Args:
- config: Feed ingestion configuration
- **kwargs: Additional configuration parameters
- """
- # TODO: Initialize feed parser
- # TODO: Setup feed monitor
- # TODO: Initialize content extractor
- # TODO: Configure update intervals
- pass
-
- def ingest_feed(self, feed_url, **options):
- """
- Ingest content from a single feed.
-
- Args:
- feed_url: URL of feed to ingest
- **options: Processing options
-
- Returns:
- FeedContent: Parsed feed content
- """
- # TODO: Validate feed URL
- # TODO: Fetch feed content
- # TODO: Parse feed format
- # TODO: Extract feed items
- # TODO: Process each item
- # TODO: Return feed content
- pass
-
- def discover_feeds(self, website_url):
- """
- Discover feeds from a website.
-
- Args:
- website_url: Website URL to scan
-
- Returns:
- list: List of discovered feed URLs
- """
- # TODO: Fetch website content
- # TODO: Look for feed links
- # TODO: Check common feed paths
- # TODO: Validate discovered feeds
- # TODO: Return feed URLs
- pass
+import requests
+import xml.etree.ElementTree as ET
+from bs4 import BeautifulSoup
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class FeedItem:
+ """Feed item representation."""
- def monitor_feeds(self, feed_urls, **options):
- """
- Monitor multiple feeds for updates.
-
- Args:
- feed_urls: List of feed URLs to monitor
- **options: Monitoring options
-
- Returns:
- FeedMonitor: Active feed monitor
- """
- # TODO: Initialize monitoring
- # TODO: Setup update checking
- # TODO: Configure notification
- # TODO: Start monitoring
- # TODO: Return monitor instance
- pass
+ title: str
+ link: str
+ description: str = ""
+ content: str = ""
+ author: str = ""
+ published: Optional[datetime] = None
+ updated: Optional[datetime] = None
+ guid: str = ""
+ categories: List[str] = field(default_factory=list)
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class FeedData:
+ """Feed data representation."""
- def extract_content(self, feed_item):
- """
- Extract content from feed item.
-
- Args:
- feed_item: Feed item to extract from
-
- Returns:
- dict: Extracted content and metadata
- """
- # TODO: Extract title
- # TODO: Extract description
- # TODO: Extract content
- # TODO: Extract metadata
- # TODO: Return content dict
- pass
+ title: str
+ link: str
+ description: str = ""
+ language: str = ""
+ updated: Optional[datetime] = None
+ items: List[FeedItem] = field(default_factory=list)
+ metadata: Dict[str, Any] = field(default_factory=dict)
class FeedParser:
@@ -137,13 +75,10 @@ class FeedParser:
Args:
**config: Parser configuration
"""
- # TODO: Initialize XML parsers
- # TODO: Setup format detectors
- # TODO: Configure content extractors
- # TODO: Setup validation
- pass
+ self.logger = get_logger("feed_parser")
+ self.config = config
- def parse_feed(self, feed_content, feed_url=None):
+ def parse_feed(self, feed_content: str, feed_url: Optional[str] = None) -> FeedData:
"""
Parse feed content and extract items.
@@ -154,15 +89,23 @@ class FeedParser:
Returns:
FeedData: Parsed feed data
"""
- # TODO: Detect feed format
- # TODO: Parse XML content
- # TODO: Extract feed metadata
- # TODO: Extract feed items
- # TODO: Validate content
- # TODO: Return feed data
- pass
+ try:
+ # Detect feed format
+ format_type = self.detect_format(feed_content)
+
+ # Parse based on format
+ if format_type == "rss":
+ return self._parse_rss(feed_content, feed_url)
+ elif format_type == "atom":
+ return self._parse_atom(feed_content, feed_url)
+ else:
+ raise ProcessingError(f"Unsupported feed format: {format_type}")
+
+ except Exception as e:
+ self.logger.error(f"Failed to parse feed: {e}")
+ raise ProcessingError(f"Failed to parse feed: {e}")
- def detect_format(self, feed_content):
+ def detect_format(self, feed_content: str) -> str:
"""
Detect feed format from content.
@@ -170,15 +113,192 @@ class FeedParser:
feed_content: Raw feed content
Returns:
- str: Detected feed format
+ str: Detected feed format (rss, atom)
"""
- # TODO: Check XML structure
- # TODO: Identify root element
- # TODO: Determine format type
- # TODO: Return format name
- pass
+ try:
+ root = ET.fromstring(feed_content)
+
+ # Check root element
+ if root.tag.endswith("feed"):
+ return "atom"
+ elif root.tag.endswith("rss") or root.tag.endswith("RDF"):
+ return "rss"
+ else:
+ # Default to RSS if unclear
+ return "rss"
+
+ except ET.ParseError:
+ # Try to detect from string content
+ content_lower = feed_content.lower()
+ if "<feed" in content_lower or "xmlns:atom" in content_lower:
+ return "atom"
+ else:
+ return "rss"
+
+ def _parse_rss(self, feed_content: str, feed_url: Optional[str] = None) -> FeedData:
+ """Parse RSS feed format."""
+ root = ET.fromstring(feed_content)
+
+ # Find channel element
+ channel = root.find("channel")
+ if channel is None:
+ raise ProcessingError("Invalid RSS feed: no channel element found")
+
+ # Extract feed metadata
+ title = self._get_text(channel.find("title"))
+ link = self._get_text(channel.find("link")) or (feed_url or "")
+ description = self._get_text(channel.find("description"))
+ language = self._get_text(channel.find("language"))
+
+ # Extract items
+ items = []
+ for item in channel.findall("item"):
+ item_title = self._get_text(item.find("title"))
+ item_link = self._get_text(item.find("link"))
+ item_description = self._get_text(item.find("description"))
+ item_guid = self._get_text(item.find("guid")) or item_link or ""
+
+ # Parse dates
+ pub_date = None
+ pub_date_elem = item.find("pubDate")
+ if pub_date_elem is not None and pub_date_elem.text:
+ pub_date = self._parse_date(pub_date_elem.text)
+
+ # Extract categories
+ categories = [cat.text for cat in item.findall("category") if cat.text]
+
+ feed_item = FeedItem(
+ title=item_title,
+ link=item_link or "",
+ description=item_description,
+ guid=item_guid,
+ published=pub_date,
+ categories=categories
+ )
+ items.append(feed_item)
+
+ return FeedData(
+ title=title,
+ link=link,
+ description=description,
+ language=language,
+ items=items
+ )
+
+ def _parse_atom(self, feed_content: str, feed_url: Optional[str] = None) -> FeedData:
+ """Parse Atom feed format."""
+ root = ET.fromstring(feed_content)
+
+ # Extract feed metadata
+ title_elem = root.find("{http://www.w3.org/2005/Atom}title")
+ title = self._get_text(title_elem) if title_elem is not None else ""
+
+ link_elem = root.find("{http://www.w3.org/2005/Atom}link[@rel='self']")
+ if link_elem is None:
+ link_elem = root.find("{http://www.w3.org/2005/Atom}link")
+ link = link_elem.get("href") if link_elem is not None else (feed_url or "")
+
+ subtitle_elem = root.find("{http://www.w3.org/2005/Atom}subtitle")
+ description = self._get_text(subtitle_elem) if subtitle_elem is not None else ""
+
+ updated_elem = root.find("{http://www.w3.org/2005/Atom}updated")
+ updated = None
+ if updated_elem is not None and updated_elem.text:
+ updated = self._parse_date(updated_elem.text)
+
+ # Extract entries
+ items = []
+ for entry in root.findall("{http://www.w3.org/2005/Atom}entry"):
+ entry_title = entry.find("{http://www.w3.org/2005/Atom}title")
+ item_title = self._get_text(entry_title) if entry_title is not None else ""
+
+ entry_link = entry.find("{http://www.w3.org/2005/Atom}link[@rel='alternate']")
+ if entry_link is None:
+ entry_link = entry.find("{http://www.w3.org/2005/Atom}link")
+ item_link = entry_link.get("href") if entry_link is not None else ""
+
+ entry_summary = entry.find("{http://www.w3.org/2005/Atom}summary")
+ entry_content = entry.find("{http://www.w3.org/2005/Atom}content")
+ description = self._get_text(entry_summary) if entry_summary is not None else ""
+ content = self._get_text(entry_content) if entry_content is not None else ""
+
+ entry_id = entry.find("{http://www.w3.org/2005/Atom}id")
+ guid = self._get_text(entry_id) if entry_id is not None else ""
+
+ # Parse dates
+ published = None
+ updated = None
+ pub_elem = entry.find("{http://www.w3.org/2005/Atom}published")
+ upd_elem = entry.find("{http://www.w3.org/2005/Atom}updated")
+ if pub_elem is not None and pub_elem.text:
+ published = self._parse_date(pub_elem.text)
+ if upd_elem is not None and upd_elem.text:
+ updated = self._parse_date(upd_elem.text)
+
+ # Extract categories
+ categories = []
+ for cat in entry.findall("{http://www.w3.org/2005/Atom}category"):
+ term = cat.get("term")
+ if term:
+ categories.append(term)
+
+ feed_item = FeedItem(
+ title=item_title,
+ link=item_link,
+ description=description,
+ content=content,
+ guid=guid,
+ published=published,
+ updated=updated,
+ categories=categories
+ )
+ items.append(feed_item)
+
+ return FeedData(
+ title=title,
+ link=link,
+ description=description,
+ updated=updated,
+ items=items
+ )
- def validate_feed(self, feed_data):
+ def _get_text(self, element) -> str:
+ """Extract text from XML element."""
+ if element is None:
+ return ""
+ return element.text or ""
+
+ def _parse_date(self, date_string: str) -> Optional[datetime]:
+ """Parse date string to datetime."""
+ from datetime import datetime as dt
+
+ # Try common date formats
+ formats = [
+ "%a, %d %b %Y %H:%M:%S %z", # RFC 822
+ "%a, %d %b %Y %H:%M:%S %Z", # RFC 822 with timezone name
+ "%Y-%m-%dT%H:%M:%S%z", # ISO 8601 with timezone
+ "%Y-%m-%dT%H:%M:%SZ", # ISO 8601 UTC
+ "%Y-%m-%dT%H:%M:%S", # ISO 8601 without timezone
+ "%Y-%m-%d %H:%M:%S", # Common format
+ "%Y-%m-%d", # Date only
+ ]
+
+ for fmt in formats:
+ try:
+ return dt.strptime(date_string.strip(), fmt)
+ except ValueError:
+ continue
+
+ # Try with dateutil if available
+ try:
+ from dateutil import parser
+ return parser.parse(date_string)
+ except ImportError:
+ pass
+
+ return None
+
+ def validate_feed(self, feed_data: FeedData) -> bool:
"""
Validate parsed feed data.
@@ -188,11 +308,19 @@ class FeedParser:
Returns:
bool: Whether feed is valid
"""
- # TODO: Check required fields
- # TODO: Validate item structure
- # TODO: Check content quality
- # TODO: Return validation result
- pass
+ # Check required fields
+ if not feed_data.title:
+ return False
+
+ if not feed_data.items:
+ return False
+
+ # Validate items
+ for item in feed_data.items:
+ if not item.title and not item.description:
+ return False
+
+ return True
class FeedMonitor:
@@ -210,13 +338,15 @@ class FeedMonitor:
Args:
**config: Monitor configuration
"""
- # TODO: Setup monitoring schedule
- # TODO: Initialize notification system
- # TODO: Configure update detection
- # TODO: Setup error handling
- pass
+ self.logger = get_logger("feed_monitor")
+ self.config = config
+ self.feeds: Dict[str, Dict[str, Any]] = {}
+ self.monitoring: bool = False
+ self.thread: Optional[threading.Thread] = None
+ self.update_callback: Optional[callable] = None
+ self.check_interval = config.get("check_interval", 3600) # Default 1 hour
- def add_feed(self, feed_url, **options):
+ def add_feed(self, feed_url: str, **options):
"""
Add feed to monitoring list.
@@ -224,32 +354,40 @@ class FeedMonitor:
feed_url: Feed URL to monitor
**options: Monitoring options
"""
- # TODO: Validate feed URL
- # TODO: Add to monitoring list
- # TODO: Setup update checking
- # TODO: Configure options
- pass
+ if not feed_url:
+ raise ValidationError("Feed URL is required")
+
+ self.feeds[feed_url] = {
+ "url": feed_url,
+ "last_check": None,
+ "last_items": [],
+ "options": options
+ }
+ self.logger.info(f"Added feed to monitoring: {feed_url}")
def start_monitoring(self):
- """
- Start monitoring all added feeds.
- """
- # TODO: Start monitoring loop
- # TODO: Schedule feed checks
- # TODO: Handle updates
- # TODO: Process new content
- pass
+ """Start monitoring all added feeds."""
+ if self.monitoring:
+ self.logger.warning("Monitoring already started")
+ return
+
+ if not self.feeds:
+ self.logger.warning("No feeds to monitor")
+ return
+
+ self.monitoring = True
+ self.thread = threading.Thread(target=self._monitoring_loop, daemon=True)
+ self.thread.start()
+ self.logger.info("Feed monitoring started")
def stop_monitoring(self):
- """
- Stop monitoring all feeds.
- """
- # TODO: Stop monitoring loop
- # TODO: Cleanup resources
- # TODO: Save state
- pass
+ """Stop monitoring all feeds."""
+ self.monitoring = False
+ if self.thread:
+ self.thread.join(timeout=5)
+ self.logger.info("Feed monitoring stopped")
- def check_updates(self, feed_url):
+ def check_updates(self, feed_url: str) -> List[FeedItem]:
"""
Check for updates in specific feed.
@@ -259,8 +397,250 @@ class FeedMonitor:
Returns:
list: List of new items
"""
- # TODO: Fetch current feed
- # TODO: Compare with previous version
- # TODO: Identify new items
- # TODO: Return new items
- pass
+ if feed_url not in self.feeds:
+ raise ValidationError(f"Feed {feed_url} not in monitoring list")
+
+ feed_info = self.feeds[feed_url]
+ parser = FeedParser()
+
+ try:
+ # Fetch feed
+ response = requests.get(feed_url, timeout=30)
+ response.raise_for_status()
+
+ # Parse feed
+ feed_data = parser.parse_feed(response.text, feed_url)
+
+ # Compare with previous items
+ last_items = feed_info["last_items"]
+ current_items = feed_data.items
+
+ # Find new items
+ if not last_items:
+ # First check - return all items
+ feed_info["last_items"] = [item.guid or item.link for item in current_items]
+ feed_info["last_check"] = datetime.now()
+ return current_items
+
+ # Find new items by comparing GUIDs/links
+ last_guids = set(last_items)
+ new_items = [
+ item for item in current_items
+ if (item.guid or item.link) not in last_guids
+ ]
+
+ # Update last items
+ feed_info["last_items"] = [item.guid or item.link for item in current_items]
+ feed_info["last_check"] = datetime.now()
+
+ return new_items
+
+ except Exception as e:
+ self.logger.error(f"Failed to check feed {feed_url}: {e}")
+ return []
+
+ def _monitoring_loop(self):
+ """Main monitoring loop."""
+ while self.monitoring:
+ for feed_url in list(self.feeds.keys()):
+ try:
+ new_items = self.check_updates(feed_url)
+ if new_items and self.update_callback:
+ self.update_callback(feed_url, new_items)
+ except Exception as e:
+ self.logger.error(f"Error checking feed {feed_url}: {e}")
+
+ # Wait for next check interval
+ time.sleep(self.check_interval)
+
+ def set_update_callback(self, callback: callable):
+ """Set callback for feed updates."""
+ self.update_callback = callback
+
+
+class FeedIngestor:
+ """
+ RSS/Atom feed ingestion handler.
+
+ Processes 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
+ """
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize feed ingestor.
+
+ Args:
+ config: Feed ingestion configuration
+ **kwargs: Additional configuration parameters
+ """
+ self.logger = get_logger("feed_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize feed parser
+ self.parser = FeedParser(**self.config)
+
+ # Setup feed monitor
+ self.monitor = FeedMonitor(**self.config)
+
+ # Update intervals
+ self.update_intervals = self.config.get("update_intervals", {})
+
+ def ingest_feed(self, feed_url: str, **options) -> FeedData:
+ """
+ Ingest content from a single feed.
+
+ Args:
+ feed_url: URL of feed to ingest
+ **options: Processing options
+
+ Returns:
+ FeedData: Parsed feed content
+ """
+ # Validate feed URL
+ try:
+ parsed = urlparse(feed_url)
+ if not parsed.scheme or not parsed.netloc:
+ raise ValidationError(f"Invalid feed URL: {feed_url}")
+ except Exception as e:
+ raise ValidationError(f"Invalid feed URL: {feed_url}") from e
+
+ # Fetch feed content
+ try:
+ timeout = options.get("timeout", self.config.get("timeout", 30))
+ response = requests.get(feed_url, timeout=timeout)
+ response.raise_for_status()
+ except requests.RequestException as e:
+ self.logger.error(f"Failed to fetch feed {feed_url}: {e}")
+ raise ProcessingError(f"Failed to fetch feed: {e}")
+
+ # Parse feed format
+ feed_data = self.parser.parse_feed(response.text, feed_url)
+
+ # Validate feed
+ if options.get("validate", True):
+ if not self.parser.validate_feed(feed_data):
+ self.logger.warning(f"Feed {feed_url} validation failed")
+
+ return feed_data
+
+ def discover_feeds(self, website_url: str) -> List[str]:
+ """
+ Discover feeds from a website.
+
+ Args:
+ website_url: Website URL to scan
+
+ Returns:
+ list: List of discovered feed URLs
+ """
+ feed_urls = []
+
+ try:
+ # Fetch website content
+ response = requests.get(website_url, timeout=30)
+ response.raise_for_status()
+
+ # Parse HTML
+ soup = BeautifulSoup(response.text, 'html.parser')
+
+ # Look for feed links
+ # Check link tags with type="application/rss+xml" or "application/atom+xml"
+ feed_links = soup.find_all('link', type=lambda t: t and ('rss' in t.lower() or 'atom' in t.lower()))
+ for link in feed_links:
+ href = link.get('href')
+ if href:
+ # Resolve relative URLs
+ feed_url = urljoin(website_url, href)
+ feed_urls.append(feed_url)
+
+ # Also check for common feed paths
+ common_paths = ['/feed', '/rss', '/atom', '/feed.xml', '/rss.xml', '/atom.xml']
+ for path in common_paths:
+ try:
+ feed_url = urljoin(website_url, path)
+ test_response = requests.head(feed_url, timeout=10)
+ if test_response.status_code == 200:
+ content_type = test_response.headers.get('Content-Type', '')
+ if 'rss' in content_type.lower() or 'atom' in content_type.lower() or 'xml' in content_type.lower():
+ if feed_url not in feed_urls:
+ feed_urls.append(feed_url)
+ except Exception:
+ continue
+
+ # Validate discovered feeds
+ validated_feeds = []
+ for feed_url in feed_urls:
+ try:
+ # Quick validation by fetching feed
+ test_response = requests.get(feed_url, timeout=10)
+ if test_response.status_code == 200:
+ validated_feeds.append(feed_url)
+ except Exception:
+ continue
+
+ return validated_feeds
+
+ except Exception as e:
+ self.logger.error(f"Failed to discover feeds from {website_url}: {e}")
+ return []
+
+ def monitor_feeds(self, feed_urls: List[str], **options) -> FeedMonitor:
+ """
+ Monitor multiple feeds for updates.
+
+ Args:
+ feed_urls: List of feed URLs to monitor
+ **options: Monitoring options
+
+ Returns:
+ FeedMonitor: Active feed monitor
+ """
+ # Add all feeds to monitor
+ for feed_url in feed_urls:
+ self.monitor.add_feed(feed_url, **options)
+
+ # Set callback if provided
+ if options.get("update_callback"):
+ self.monitor.set_update_callback(options["update_callback"])
+
+ # Start monitoring if requested
+ if options.get("start", True):
+ self.monitor.start_monitoring()
+
+ return self.monitor
+
+ def extract_content(self, feed_item: FeedItem) -> Dict[str, Any]:
+ """
+ Extract content from feed item.
+
+ Args:
+ feed_item: Feed item to extract from
+
+ Returns:
+ dict: Extracted content and metadata
+ """
+ return {
+ "title": feed_item.title,
+ "description": feed_item.description,
+ "content": feed_item.content or feed_item.description,
+ "link": feed_item.link,
+ "author": feed_item.author,
+ "published": feed_item.published.isoformat() if feed_item.published else None,
+ "updated": feed_item.updated.isoformat() if feed_item.updated else None,
+ "categories": feed_item.categories,
+ "guid": feed_item.guid,
+ "metadata": feed_item.metadata
+ }
diff --git a/libs/semantica/ingest/file_ingestor.py b/libs/semantica/ingest/file_ingestor.py
index b6df34df..48aecfb3 100644
--- a/libs/semantica/ingest/file_ingestor.py
+++ b/libs/semantica/ingest/file_ingestor.py
@@ -16,116 +16,125 @@ Main Classes:
- FileTypeDetector: File type identification
"""
+import mimetypes
+import os
+from pathlib import Path
+from typing import Any, Dict, List, Optional, Union
+from dataclasses import dataclass, field
+from datetime import datetime
-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.
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+from ..utils.constants import (
+ SUPPORTED_DOCUMENT_FORMATS,
+ SUPPORTED_IMAGE_FORMATS,
+ SUPPORTED_AUDIO_FORMATS,
+ SUPPORTED_VIDEO_FORMATS,
+ FILE_SIZE_LIMITS
+)
+
+
+@dataclass
+class FileObject:
+ """File object representation."""
- 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
+ path: str
+ name: str
+ size: int
+ file_type: str
+ mime_type: Optional[str] = None
+ content: Optional[bytes] = None
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ ingested_at: datetime = field(default_factory=datetime.now)
+
+
+class FileTypeDetector:
"""
+ File type detection and validation.
- def __init__(self, config=None, **kwargs):
- """
- Initialize file ingestor.
-
- Args:
- config: Ingestion configuration
- **kwargs: Additional configuration parameters
- """
- # TODO: Initialize configuration
- # TODO: Setup file type detectors
- # TODO: Initialize cloud providers
- # TODO: Setup progress tracking
- pass
+ Identifies file types using multiple methods including
+ extension, MIME type, and content analysis.
+ """
- def ingest_directory(self, directory_path, recursive=True, **filters):
- """
- Ingest all files from a directory.
-
- Args:
- directory_path: Path to directory
- recursive: Whether to scan subdirectories
- **filters: File filtering criteria
-
- Returns:
- list: List of ingested file objects
- """
- # TODO: Validate directory path
- # TODO: Scan directory for files
- # TODO: Apply file filters
- # TODO: Process each file
- # TODO: Track progress
- # TODO: Return file objects
- pass
+ def __init__(self):
+ """Initialize file type detector."""
+ self.logger = get_logger("file_type_detector")
+ self.supported_formats = (
+ SUPPORTED_DOCUMENT_FORMATS +
+ SUPPORTED_IMAGE_FORMATS +
+ SUPPORTED_AUDIO_FORMATS +
+ SUPPORTED_VIDEO_FORMATS
+ )
+ # Initialize MIME types database
+ mimetypes.init()
- def ingest_file(self, file_path, **options):
+ def detect_type(self, file_path: Union[str, Path], content: Optional[bytes] = None) -> str:
"""
- Ingest a single file.
+ Detect file type using multiple methods.
Args:
file_path: Path to file
- **options: Processing options
+ content: Optional file content
Returns:
- FileObject: Ingested file object
+ str: Detected file type
"""
- # TODO: Validate file path
- # TODO: Check file exists
- # TODO: Detect file type
- # TODO: Read file content
- # TODO: Create file object
- # TODO: Return file object
- pass
+ file_path = Path(file_path)
+
+ # Method 1: Check file extension
+ extension = file_path.suffix.lstrip('.').lower()
+ if extension:
+ return extension
+
+ # Method 2: Check MIME type
+ if file_path.exists():
+ mime_type, _ = mimetypes.guess_type(str(file_path))
+ if mime_type:
+ # Map MIME type to extension
+ ext = mimetypes.guess_extension(mime_type)
+ if ext:
+ return ext.lstrip('.').lower()
+
+ # Method 3: Check magic numbers if content provided
+ if content:
+ file_type = self._detect_by_magic_numbers(content)
+ if file_type:
+ return file_type
+
+ return "unknown"
- def ingest_cloud(self, provider, bucket, prefix="", **config):
- """
- Ingest files from cloud storage.
+ def _detect_by_magic_numbers(self, content: bytes) -> Optional[str]:
+ """Detect file type by magic numbers (file signatures)."""
+ if len(content) < 4:
+ return None
- Args:
- provider: Cloud provider (s3, gcs, azure)
- bucket: Storage bucket name
- prefix: Object prefix filter
- **config: Cloud provider configuration
-
- Returns:
- list: List of ingested file objects
- """
- # TODO: Initialize cloud client
- # TODO: List objects in bucket
- # TODO: Filter by prefix
- # TODO: Download objects
- # TODO: Process each file
- # TODO: Return file objects
- pass
+ # Common magic numbers
+ 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)
+ }
+
+ for magic, file_type in magic_numbers.items():
+ if content.startswith(magic):
+ return file_type
+
+ return None
- def scan_directory(self, directory_path, **filters):
+ def is_supported(self, file_type: str) -> bool:
"""
- Scan directory and return file information without processing.
+ Check if file type is supported.
Args:
- directory_path: Path to directory
- **filters: File filtering criteria
+ file_type: File type to check
Returns:
- list: List of file metadata
+ bool: Whether type is supported
"""
- # TODO: Walk directory tree
- # TODO: Collect file metadata
- # TODO: Apply filters
- # TODO: Return file list
- pass
+ return file_type.lower() in self.supported_formats
class CloudStorageIngestor:
@@ -136,21 +145,44 @@ class CloudStorageIngestor:
from various cloud storage providers.
"""
- def __init__(self, provider, **config):
+ def __init__(self, provider: str, **config):
"""
Initialize cloud storage ingestor.
Args:
- provider: Cloud provider name
+ provider: Cloud provider name (s3, gcs, azure)
**config: Provider-specific configuration
"""
- # TODO: Initialize cloud client
- # TODO: Setup authentication
- # TODO: Configure retry policies
- # TODO: Setup monitoring
- pass
+ self.logger = get_logger("cloud_storage_ingestor")
+ self.provider = provider.lower()
+ self.config = config
+ self._client = None
+
+ # Initialize provider-specific client
+ self._initialize_client()
+
+ def _initialize_client(self):
+ """Initialize cloud storage client based on provider."""
+ if self.provider == "s3":
+ import boto3
+ self._client = boto3.client(
+ 's3',
+ aws_access_key_id=self.config.get('access_key_id'),
+ aws_secret_access_key=self.config.get('secret_access_key'),
+ region_name=self.config.get('region', 'us-east-1')
+ )
+ elif self.provider == "gcs":
+ from google.cloud import storage
+ self._client = storage.Client()
+ elif self.provider == "azure":
+ from azure.storage.blob import BlobServiceClient
+ self._client = BlobServiceClient.from_connection_string(
+ self.config.get('connection_string')
+ )
+ else:
+ raise ValueError(f"Unsupported cloud provider: {self.provider}")
- def list_objects(self, bucket, prefix="", **filters):
+ def list_objects(self, bucket: str, prefix: str = "", **filters) -> List[Dict[str, Any]]:
"""
List objects in cloud storage.
@@ -162,13 +194,72 @@ class CloudStorageIngestor:
Returns:
list: List of object metadata
"""
- # TODO: Call cloud API
- # TODO: Apply filters
- # TODO: Handle pagination
- # TODO: Return object list
- pass
+ try:
+ objects = []
+
+ if self.provider == "s3":
+ paginator = self._client.get_paginator('list_objects_v2')
+ pages = paginator.paginate(Bucket=bucket, Prefix=prefix)
+
+ for page in pages:
+ if 'Contents' in page:
+ for obj in page['Contents']:
+ objects.append({
+ 'key': obj['Key'],
+ 'size': obj['Size'],
+ 'last_modified': obj['LastModified'],
+ 'etag': obj['ETag']
+ })
+ elif self.provider == "gcs":
+ bucket_obj = self._client.bucket(bucket)
+ blobs = bucket_obj.list_blobs(prefix=prefix)
+
+ for blob in blobs:
+ objects.append({
+ 'key': blob.name,
+ 'size': blob.size,
+ 'last_modified': blob.updated,
+ 'etag': blob.etag
+ })
+ elif self.provider == "azure":
+ container_client = self._client.get_container_client(bucket)
+ blobs = container_client.list_blobs(name_starts_with=prefix)
+
+ for blob in blobs:
+ objects.append({
+ 'key': blob.name,
+ 'size': blob.size,
+ 'last_modified': blob.last_modified,
+ 'etag': blob.etag
+ })
+
+ # Apply additional filters
+ if filters:
+ objects = self._apply_filters(objects, filters)
+
+ return objects
+
+ except Exception as e:
+ self.logger.error(f"Failed to list objects from {self.provider}: {e}")
+ raise ProcessingError(f"Failed to list objects: {e}")
- def download_object(self, bucket, key, **options):
+ def _apply_filters(self, objects: List[Dict[str, Any]], filters: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Apply filters to object list."""
+ filtered = objects
+
+ if 'min_size' in filters:
+ filtered = [obj for obj in filtered if obj['size'] >= filters['min_size']]
+
+ if 'max_size' in filters:
+ filtered = [obj for obj in filtered if obj['size'] <= filters['max_size']]
+
+ if 'extensions' in filters:
+ exts = filters['extensions']
+ filtered = [obj for obj in filtered if Path(obj['key']).suffix.lstrip('.') in exts]
+
+ return filtered
+
+ def download_object(self, bucket: str, key: str, **options) -> bytes:
"""
Download object from cloud storage.
@@ -180,57 +271,320 @@ class CloudStorageIngestor:
Returns:
bytes: Object content
"""
- # TODO: Download object
- # TODO: Handle errors
- # TODO: Apply options
- # TODO: Return content
- pass
+ try:
+ if self.provider == "s3":
+ response = self._client.get_object(Bucket=bucket, Key=key)
+ content = response['Body'].read()
+ elif self.provider == "gcs":
+ bucket_obj = self._client.bucket(bucket)
+ blob = bucket_obj.blob(key)
+ content = blob.download_as_bytes()
+ elif self.provider == "azure":
+ container_client = self._client.get_container_client(bucket)
+ blob_client = container_client.get_blob_client(key)
+ content = blob_client.download_blob().readall()
+ else:
+ raise ValueError(f"Unsupported provider: {self.provider}")
+
+ return content
+
+ except Exception as e:
+ self.logger.error(f"Failed to download object {key} from {self.provider}: {e}")
+ raise ProcessingError(f"Failed to download object: {e}")
-class FileTypeDetector:
+class FileIngestor:
"""
- File type detection and validation.
+ File system and cloud storage ingestion handler.
- Identifies file types using multiple methods including
- extension, MIME type, and content analysis.
+ Supports local files, cloud storage (S3, GCS, Azure), and
+ various file formats with automatic type detection.
+
+ 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
"""
- def __init__(self):
- """Initialize file type detector."""
- # TODO: Load MIME type database
- # TODO: Setup magic number detection
- # TODO: Initialize content analyzers
- # TODO: Setup extension mapping
- pass
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
+ """
+ Initialize file ingestor.
+
+ Args:
+ config: Ingestion configuration
+ **kwargs: Additional configuration parameters
+ """
+ self.logger = get_logger("file_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize file type detector
+ self.type_detector = FileTypeDetector()
+ self.supported_formats = self.type_detector.supported_formats
+
+ # Cloud providers (lazy initialization)
+ self._cloud_providers: Dict[str, CloudStorageIngestor] = {}
+
+ # Progress tracking
+ self._progress_callback = None
- def detect_type(self, file_path, content=None):
+ def ingest_directory(
+ self,
+ directory_path: Union[str, Path],
+ recursive: bool = True,
+ **filters
+ ) -> List[FileObject]:
"""
- Detect file type using multiple methods.
+ Ingest all files from a directory.
+
+ Args:
+ directory_path: Path to directory
+ recursive: Whether to scan subdirectories
+ **filters: File filtering criteria
+
+ Returns:
+ list: List of ingested file objects
+ """
+ directory_path = Path(directory_path)
+
+ # Validate directory path
+ if not directory_path.exists():
+ raise ValidationError(f"Directory not found: {directory_path}")
+
+ if not directory_path.is_dir():
+ raise ValidationError(f"Path is not a directory: {directory_path}")
+
+ # Scan directory for files
+ files = self.scan_directory(directory_path, recursive=recursive, **filters)
+
+ # Process each file
+ file_objects = []
+ total_files = len(files)
+
+ for idx, file_info in enumerate(files, 1):
+ try:
+ file_obj = self.ingest_file(file_info['path'], **file_info)
+ file_objects.append(file_obj)
+
+ # Track progress
+ if self._progress_callback:
+ self._progress_callback(idx, total_files, file_obj)
+
+ self.logger.debug(f"Ingested file {idx}/{total_files}: {file_info['path']}")
+
+ except Exception as e:
+ self.logger.error(f"Failed to ingest file {file_info['path']}: {e}")
+ if self.config.get('fail_fast', False):
+ raise ProcessingError(f"Failed to ingest file: {e}")
+
+ return file_objects
+
+ def ingest_file(self, file_path: Union[str, Path], **options) -> FileObject:
+ """
+ Ingest a single file.
Args:
file_path: Path to file
- content: Optional file content
+ **options: Processing options
Returns:
- str: Detected file type
+ FileObject: Ingested file object
"""
- # TODO: Check file extension
- # TODO: Analyze MIME type
- # TODO: Check magic numbers
- # TODO: Analyze content if available
- # TODO: Return detected type
- pass
+ file_path = Path(file_path)
+
+ # Validate file path
+ if not file_path.exists():
+ raise ValidationError(f"File not found: {file_path}")
+
+ if not file_path.is_file():
+ raise ValidationError(f"Path is not a file: {file_path}")
+
+ # Check file size limits
+ file_size = file_path.stat().st_size
+ max_size = FILE_SIZE_LIMITS.get('MAX_DOCUMENT_SIZE', 104857600)
+ if file_size > max_size:
+ raise ValidationError(f"File size {file_size} exceeds maximum {max_size}")
+
+ # Detect file type
+ file_type = self.type_detector.detect_type(file_path)
+
+ if not self.type_detector.is_supported(file_type):
+ self.logger.warning(f"Unsupported file type: {file_type} for {file_path}")
+
+ # Read file content if requested
+ content = None
+ if options.get('read_content', True):
+ try:
+ with open(file_path, 'rb') as f:
+ content = f.read()
+ except Exception as e:
+ self.logger.error(f"Failed to read file content: {e}")
+ raise ProcessingError(f"Failed to read file: {e}")
+
+ # Get MIME type
+ mime_type, _ = mimetypes.guess_type(str(file_path))
+
+ # Create file object
+ file_obj = FileObject(
+ path=str(file_path),
+ name=file_path.name,
+ size=file_size,
+ file_type=file_type,
+ mime_type=mime_type,
+ content=content,
+ metadata={
+ 'extension': file_path.suffix,
+ 'parent': str(file_path.parent),
+ 'is_supported': self.type_detector.is_supported(file_type),
+ **options
+ }
+ )
+
+ return file_obj
- def is_supported(self, file_type):
+ def ingest_cloud(
+ self,
+ provider: str,
+ bucket: str,
+ prefix: str = "",
+ **config
+ ) -> List[FileObject]:
"""
- Check if file type is supported.
+ Ingest files from cloud storage.
Args:
- file_type: File type to check
+ provider: Cloud provider (s3, gcs, azure)
+ bucket: Storage bucket name
+ prefix: Object prefix filter
+ **config: Cloud provider configuration
Returns:
- bool: Whether type is supported
+ list: List of ingested file objects
+ """
+ # Initialize cloud client if not already done
+ if provider not in self._cloud_providers:
+ self._cloud_providers[provider] = CloudStorageIngestor(provider, **config)
+
+ cloud_ingestor = self._cloud_providers[provider]
+
+ # List objects in bucket
+ objects = cloud_ingestor.list_objects(bucket, prefix=prefix)
+
+ # Process each object
+ file_objects = []
+
+ for obj_info in objects:
+ try:
+ # Download object
+ content = cloud_ingestor.download_object(bucket, obj_info['key'])
+
+ # Detect file type
+ file_type = self.type_detector._detect_by_magic_numbers(content) or \
+ self.type_detector.detect_type(obj_info['key'])
+
+ # Create file object
+ file_obj = FileObject(
+ path=obj_info['key'],
+ name=Path(obj_info['key']).name,
+ size=obj_info['size'],
+ file_type=file_type,
+ content=content,
+ metadata={
+ 'provider': provider,
+ 'bucket': bucket,
+ 'etag': obj_info.get('etag'),
+ 'last_modified': str(obj_info.get('last_modified')),
+ }
+ )
+
+ file_objects.append(file_obj)
+
+ except Exception as e:
+ self.logger.error(f"Failed to ingest object {obj_info['key']}: {e}")
+ if self.config.get('fail_fast', False):
+ raise ProcessingError(f"Failed to ingest object: {e}")
+
+ return file_objects
+
+ def scan_directory(
+ self,
+ directory_path: Union[str, Path],
+ **filters
+ ) -> List[Dict[str, Any]]:
+ """
+ Scan directory and return file information without processing.
+
+ Args:
+ directory_path: Path to directory
+ **filters: File filtering criteria:
+ - recursive: Whether to scan subdirectories (default: True)
+ - extensions: List of allowed extensions
+ - min_size: Minimum file size
+ - max_size: Maximum file size
+ - pattern: Filename pattern (glob)
+
+ Returns:
+ list: List of file metadata
"""
- # TODO: Check against supported types
- # TODO: Return boolean result
- pass
+ directory_path = Path(directory_path)
+ recursive = filters.pop('recursive', True)
+
+ # Walk directory tree
+ files = []
+
+ if recursive:
+ for file_path in directory_path.rglob('*'):
+ if file_path.is_file():
+ files.append(self._get_file_info(file_path))
+ else:
+ for file_path in directory_path.iterdir():
+ if file_path.is_file():
+ files.append(self._get_file_info(file_path))
+
+ # Apply filters
+ if filters:
+ files = self._apply_file_filters(files, filters)
+
+ return files
+
+ def _get_file_info(self, file_path: Path) -> Dict[str, Any]:
+ """Get file information."""
+ stat = file_path.stat()
+ return {
+ 'path': str(file_path),
+ 'name': file_path.name,
+ 'size': stat.st_size,
+ 'extension': file_path.suffix.lstrip('.'),
+ 'modified': stat.st_mtime,
+ }
+
+ def _apply_file_filters(self, files: List[Dict[str, Any]], filters: Dict[str, Any]) -> List[Dict[str, Any]]:
+ """Apply filters to file list."""
+ filtered = files
+
+ if 'extensions' in filters:
+ exts = [ext.lstrip('.') for ext in filters['extensions']]
+ filtered = [f for f in filtered if f['extension'] in exts]
+
+ if 'min_size' in filters:
+ filtered = [f for f in filtered if f['size'] >= filters['min_size']]
+
+ if 'max_size' in filters:
+ filtered = [f for f in filtered if f['size'] <= filters['max_size']]
+
+ if 'pattern' in filters:
+ import fnmatch
+ pattern = filters['pattern']
+ filtered = [f for f in filtered if fnmatch.fnmatch(f['name'], pattern)]
+
+ return filtered
+
+ def set_progress_callback(self, callback):
+ """Set progress tracking callback."""
+ self._progress_callback = callback
diff --git a/libs/semantica/ingest/repo_ingestor.py b/libs/semantica/ingest/repo_ingestor.py
index 95e04eff..0b6856f6 100644
--- a/libs/semantica/ingest/repo_ingestor.py
+++ b/libs/semantica/ingest/repo_ingestor.py
@@ -16,211 +16,650 @@ Main Classes:
- CodeExtractor: Code content extractor
"""
+import os
+import re
+import shutil
+import tempfile
+from dataclasses import dataclass, field
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional
-class RepoIngestor:
- """
- Git repository ingestion handler.
+import git
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class CodeFile:
+ """Code file representation."""
- • Clones and analyzes Git repositories
- • Extracts code files and documentation
- • Processes commit history and metadata
- • Analyzes repository structure and branches
- • Supports various Git hosting platforms
+ path: str
+ name: str
+ language: str
+ content: str
+ size: int
+ lines: int
+ metadata: Dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class CommitInfo:
+ """Commit information representation."""
- 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
+ hash: str
+ message: str
+ author: str
+ date: datetime
+ files_changed: List[str] = field(default_factory=list)
+ additions: int = 0
+ deletions: int = 0
+
+
+class CodeExtractor:
+ """
+ Code content extraction and processing.
+
+ Extracts code content from various file types
+ and processes different programming languages.
"""
- def __init__(self, config=None, **kwargs):
+ # File extension to language mapping
+ LANGUAGE_MAP = {
+ '.py': 'python',
+ '.js': 'javascript',
+ '.ts': 'typescript',
+ '.java': 'java',
+ '.cpp': 'cpp',
+ '.c': 'c',
+ '.cs': 'csharp',
+ '.go': 'go',
+ '.rs': 'rust',
+ '.rb': 'ruby',
+ '.php': 'php',
+ '.swift': 'swift',
+ '.kt': 'kotlin',
+ '.scala': 'scala',
+ '.r': 'r',
+ '.m': 'matlab',
+ '.sh': 'shell',
+ '.sql': 'sql',
+ '.html': 'html',
+ '.css': 'css',
+ '.scss': 'scss',
+ '.json': 'json',
+ '.xml': 'xml',
+ '.yaml': 'yaml',
+ '.yml': 'yaml',
+ '.md': 'markdown',
+ '.txt': 'text',
+ }
+
+ def __init__(self, **config):
"""
- Initialize repository ingestor.
+ Initialize code extractor.
- • Setup Git client configuration
- • Initialize code extraction tools
- • Configure repository analysis settings
- • Setup temporary directory for cloning
- • Initialize supported platform handlers
+ Args:
+ **config: Extraction configuration
"""
- pass
+ self.logger = get_logger("code_extractor")
+ self.config = config
- def ingest_repository(self, repo_url, **options):
+ def extract_file_content(self, file_path: Path, language: Optional[str] = None) -> CodeFile:
"""
- Ingest and process a Git repository.
+ Extract content from code file.
- • Validate repository URL format
- • Clone repository to temporary location
- • Extract repository metadata and information
- • Process all code files in repository
- • Analyze commit history and contributors
- • Extract documentation and README files
- • Generate repository structure analysis
- • Return processed repository data
+ Args:
+ file_path: Path to code file
+ language: Programming language (auto-detected if not provided)
+
+ Returns:
+ CodeFile: Extracted code file data
"""
- pass
+ if not file_path.exists():
+ raise ValidationError(f"File not found: {file_path}")
+
+ # Detect language if not provided
+ if language is None:
+ language = self._detect_language(file_path)
+
+ # Read file content
+ try:
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
+ content = f.read()
+ except Exception as e:
+ self.logger.warning(f"Failed to read file {file_path}: {e}")
+ content = ""
+
+ # Get file stats
+ stat = file_path.stat()
+ lines = content.count('\n') + (1 if content else 0)
+
+ # Extract metadata
+ metadata = {
+ "extension": file_path.suffix,
+ "size_bytes": stat.st_size,
+ "modified": datetime.fromtimestamp(stat.st_mtime)
+ }
+
+ # Extract structure if supported
+ if language in ['python', 'javascript', 'typescript', 'java']:
+ metadata["structure"] = self._extract_structure(content, language)
+
+ return CodeFile(
+ path=str(file_path),
+ name=file_path.name,
+ language=language,
+ content=content,
+ size=stat.st_size,
+ lines=lines,
+ metadata=metadata
+ )
- def analyze_commits(self, repo_path, **filters):
+ def extract_documentation(self, file_path: Path) -> Dict[str, Any]:
"""
- Analyze commit history and patterns.
+ Extract documentation from code file.
- • Parse Git log and commit data
- • Extract commit messages and metadata
- • Analyze commit frequency and patterns
- • Identify major contributors and changes
- • Extract commit diffs and file changes
- • Apply filtering criteria if provided
- • Return commit analysis results
+ Args:
+ file_path: Path to code file
+
+ Returns:
+ dict: Documentation content
"""
- pass
+ language = self._detect_language(file_path)
+ docs = {
+ "docstrings": [],
+ "comments": [],
+ "readme": None
+ }
+
+ if file_path.name.lower() in ['readme.md', 'readme.txt', 'readme']:
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
+ docs["readme"] = f.read()
+ return docs
+
+ try:
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
+ content = f.read()
+ except Exception:
+ return docs
+
+ # Extract docstrings (Python style)
+ if language == 'python':
+ docstring_pattern = r'"""(.*?)"""'
+ matches = re.findall(docstring_pattern, content, re.DOTALL)
+ docs["docstrings"] = [m.strip() for m in matches]
+
+ # Extract comments
+ comment_patterns = {
+ 'python': r'#\s*(.*)',
+ 'javascript': r'//\s*(.*)',
+ 'java': r'//\s*(.*)',
+ 'c': r'//\s*(.*)',
+ 'cpp': r'//\s*(.*)',
+ }
+
+ if language in comment_patterns:
+ pattern = comment_patterns[language]
+ matches = re.findall(pattern, content, re.MULTILINE)
+ docs["comments"] = [m.strip() for m in matches if m.strip()]
+
+ return docs
- def extract_code_files(self, repo_path, **filters):
+ def analyze_dependencies(self, file_path: Path) -> Dict[str, Any]:
"""
- Extract and process code files from repository.
+ Analyze file dependencies and imports.
- • Scan repository for code files
- • Identify file types and languages
- • Extract file content and metadata
- • Apply language-specific processing
- • Filter files based on criteria
- • Extract code structure and dependencies
- • Return processed code files
+ Args:
+ file_path: Path to code file
+
+ Returns:
+ dict: Dependency analysis
"""
- pass
+ language = self._detect_language(file_path)
+ dependencies = {
+ "external": [],
+ "internal": [],
+ "language": language
+ }
+
+ try:
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
+ content = f.read()
+ except Exception:
+ return dependencies
+
+ # Python imports
+ if language == 'python':
+ import_pattern = r'^(?:from|import)\s+([\w.]+)'
+ matches = re.findall(import_pattern, content, re.MULTILINE)
+ dependencies["external"] = matches
+
+ # JavaScript/TypeScript imports
+ elif language in ['javascript', 'typescript']:
+ import_pattern = r"(?:import|require)\(?['\"]([^'\"]+)['\"]"
+ matches = re.findall(import_pattern, content)
+ dependencies["external"] = matches
+
+ # Java imports
+ elif language == 'java':
+ import_pattern = r'^import\s+([\w.]+)'
+ matches = re.findall(import_pattern, content, re.MULTILINE)
+ dependencies["external"] = matches
+
+ return dependencies
- def get_repository_info(self, repo_url):
- """
- Get repository metadata and information.
+ def _detect_language(self, file_path: Path) -> str:
+ """Detect programming language from file extension."""
+ ext = file_path.suffix.lower()
+ return self.LANGUAGE_MAP.get(ext, 'unknown')
+
+ def _extract_structure(self, content: str, language: str) -> Dict[str, Any]:
+ """Extract code structure (functions, classes, etc.)."""
+ structure = {
+ "classes": [],
+ "functions": [],
+ "imports": []
+ }
- • Fetch repository metadata from hosting platform
- • Extract repository description and topics
- • Get star count and fork information
- • Extract license and language information
- • Get contributor and activity statistics
- • Return repository information dictionary
- """
- pass
+ if language == 'python':
+ # Extract classes
+ class_pattern = r'^class\s+(\w+)'
+ structure["classes"] = re.findall(class_pattern, content, re.MULTILINE)
+
+ # Extract functions
+ func_pattern = r'^def\s+(\w+)'
+ structure["functions"] = re.findall(func_pattern, content, re.MULTILINE)
+
+ elif language in ['javascript', 'typescript']:
+ # Extract classes
+ class_pattern = r'class\s+(\w+)'
+ structure["classes"] = re.findall(class_pattern, content)
+
+ # Extract functions
+ func_pattern = r'function\s+(\w+)|const\s+(\w+)\s*=\s*(?:async\s+)?\(|(\w+)\s*:\s*(?:async\s+)?\(.*?\)\s*=>
+ matches = re.findall(func_pattern, content)
+ structure["functions"] = [m[0] or m[1] or m[2] for m in matches if any(m)]
+
+ return structure
class GitAnalyzer:
"""
Git repository analysis and statistics.
- • Analyzes repository structure and history
- • Calculates code metrics and statistics
- • Identifies code patterns and trends
- • Extracts development insights
+ Analyzes repository structure and history,
+ calculates code metrics and statistics.
"""
def __init__(self, **config):
"""
Initialize Git analyzer.
- • Setup Git command interface
- • Configure analysis parameters
- • Initialize metrics calculators
- • Setup pattern detection tools
+ Args:
+ **config: Analyzer configuration
"""
- pass
+ self.logger = get_logger("git_analyzer")
+ self.config = config
- def analyze_structure(self, repo_path):
+ def analyze_structure(self, repo_path: Path) -> Dict[str, Any]:
"""
Analyze repository file structure.
- • Scan directory tree and file organization
- • Identify project structure patterns
- • Calculate file size and type distributions
- • Analyze directory depth and organization
- • Return structure analysis results
+ Args:
+ repo_path: Path to repository
+
+ Returns:
+ dict: Structure analysis results
"""
- pass
+ structure = {
+ "total_files": 0,
+ "total_directories": 0,
+ "file_types": {},
+ "directory_structure": {},
+ "max_depth": 0
+ }
+
+ def analyze_dir(path: Path, depth: int = 0):
+ structure["max_depth"] = max(structure["max_depth"], depth)
+
+ try:
+ items = list(path.iterdir())
+ for item in items:
+ if item.is_file():
+ structure["total_files"] += 1
+ ext = item.suffix.lower() or 'no_extension'
+ structure["file_types"][ext] = structure["file_types"].get(ext, 0) + 1
+ elif item.is_dir() and item.name not in ['.git', '__pycache__', 'node_modules']:
+ structure["total_directories"] += 1
+ analyze_dir(item, depth + 1)
+ except PermissionError:
+ pass
+
+ analyze_dir(repo_path)
+ return structure
- def calculate_metrics(self, repo_path):
+ def calculate_metrics(self, repo_path: Path) -> Dict[str, Any]:
"""
Calculate repository metrics and statistics.
- • Count lines of code by language
- • Calculate file and directory counts
- • Measure repository size and complexity
- • Analyze code duplication and patterns
- • Return metrics dictionary
+ Args:
+ repo_path: Path to repository
+
+ Returns:
+ dict: Metrics dictionary
"""
- pass
+ metrics = {
+ "total_lines": 0,
+ "total_files": 0,
+ "lines_by_language": {},
+ "files_by_language": {}
+ }
+
+ extractor = CodeExtractor()
+
+ for file_path in repo_path.rglob('*'):
+ if file_path.is_file() and file_path.name not in ['.gitignore', '.gitkeep']:
+ try:
+ code_file = extractor.extract_file_content(file_path)
+ metrics["total_files"] += 1
+ metrics["total_lines"] += code_file.lines
+
+ lang = code_file.language
+ metrics["lines_by_language"][lang] = metrics["lines_by_language"].get(lang, 0) + code_file.lines
+ metrics["files_by_language"][lang] = metrics["files_by_language"].get(lang, 0) + 1
+ except Exception:
+ continue
+
+ return metrics
- def detect_patterns(self, repo_path):
+ def detect_patterns(self, repo_path: Path) -> Dict[str, Any]:
"""
Detect code patterns and conventions.
- • Identify coding style patterns
- • Detect architectural patterns
- • Find common code structures
- • Analyze naming conventions
- • Return pattern analysis results
+ Args:
+ repo_path: Path to repository
+
+ Returns:
+ dict: Pattern analysis results
"""
- pass
+ patterns = {
+ "naming_conventions": {},
+ "file_organization": {},
+ "common_structures": []
+ }
+
+ # Analyze naming patterns
+ python_files = list(repo_path.rglob('*.py'))
+ if python_files:
+ patterns["naming_conventions"]["python"] = "detected"
+
+ return patterns
-class CodeExtractor:
+class RepoIngestor:
"""
- Code content extraction and processing.
+ Git repository ingestion handler.
+
+ Clones and analyzes Git repositories,
+ extracts code files and documentation,
+ and processes commit history and metadata.
- • Extracts code content from various file types
- • Processes different programming languages
- • Handles code comments and documentation
- • Extracts code structure and dependencies
+ 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
"""
- def __init__(self, **config):
+ SUPPORTED_PLATFORMS = ['github', 'gitlab', 'bitbucket', 'generic']
+
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
- Initialize code extractor.
+ Initialize repository ingestor.
- • Setup language-specific parsers
- • Configure content extraction rules
- • Initialize comment and docstring extractors
- • Setup dependency analysis tools
+ Args:
+ config: Repository ingestion configuration
+ **kwargs: Additional configuration parameters
"""
- pass
+ self.logger = get_logger("repo_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize code extractor
+ self.code_extractor = CodeExtractor(**self.config)
+
+ # Initialize analyzer
+ self.analyzer = GitAnalyzer(**self.config)
+
+ # Temporary directory for cloning
+ self.temp_dir = None
- def extract_file_content(self, file_path, language=None):
+ def ingest_repository(self, repo_url: str, **options) -> Dict[str, Any]:
"""
- Extract content from code file.
+ Ingest and process a Git repository.
+
+ Args:
+ repo_url: Repository URL
+ **options: Processing options:
+ - branch: Specific branch to checkout
+ - depth: Clone depth (for shallow clones)
+ - include_history: Whether to include commit history
+
+ Returns:
+ dict: Processed repository data
+ """
+ # Validate repository URL
+ try:
+ parsed = git.Repo.clone_from(repo_url, self._get_temp_dir(), **options)
+ except Exception as e:
+ raise ProcessingError(f"Failed to clone repository: {e}")
+
+ repo_path = Path(self.temp_dir)
+ repo = git.Repo(repo_path)
+
+ # Checkout specific branch if requested
+ if options.get("branch"):
+ try:
+ repo.git.checkout(options["branch"])
+ except Exception as e:
+ self.logger.warning(f"Failed to checkout branch {options['branch']}: {e}")
+
+ # Extract repository information
+ repo_info = self.get_repository_info(repo_url, repo)
+
+ # Process code files
+ code_files = self.extract_code_files(repo_path, **options.get("file_filters", {}))
+
+ # Analyze commits if requested
+ commits = []
+ if options.get("include_history", True):
+ commits = self.analyze_commits(repo_path, **options.get("commit_filters", {}))
+
+ # Analyze structure
+ structure = self.analyzer.analyze_structure(repo_path)
+ metrics = self.analyzer.calculate_metrics(repo_path)
- • Detect file language if not specified
- • Parse file content and structure
- • Extract code, comments, and docstrings
- • Identify functions, classes, and variables
- • Extract import statements and dependencies
- • Return structured code content
+ return {
+ "repository_info": repo_info,
+ "code_files": [f.__dict__ for f in code_files],
+ "commits": [c.__dict__ for c in commits],
+ "structure": structure,
+ "metrics": metrics,
+ "temp_path": str(repo_path)
+ }
+
+ def analyze_commits(self, repo_path: Path, **filters) -> List[CommitInfo]:
+ """
+ Analyze commit history and patterns.
+
+ Args:
+ repo_path: Path to repository
+ **filters: Filtering criteria:
+ - since: Date to start from
+ - until: Date to end at
+ - author: Filter by author
+ - max_commits: Maximum number of commits
+
+ Returns:
+ list: Commit analysis results
"""
- pass
+ try:
+ repo = git.Repo(repo_path)
+ except Exception as e:
+ raise ProcessingError(f"Failed to open repository: {e}")
+
+ commits = []
+
+ # Build git log arguments
+ log_args = []
+ if filters.get("since"):
+ log_args.append(f'--since={filters["since"]}')
+ if filters.get("until"):
+ log_args.append(f'--until={filters["until"]}')
+ if filters.get("author"):
+ log_args.append(f'--author={filters["author"]}')
+ if filters.get("max_commits"):
+ log_args.append(f'-{filters["max_commits"]}')
+
+ try:
+ for commit in repo.iter_commits(*log_args):
+ # Get files changed
+ files_changed = [item.a_path for item in commit.stats.files.keys()]
+
+ # Calculate stats
+ stats = commit.stats.total
+
+ commit_info = CommitInfo(
+ hash=commit.hexsha[:7],
+ message=commit.message.strip(),
+ author=str(commit.author),
+ date=datetime.fromtimestamp(commit.committed_date),
+ files_changed=files_changed,
+ additions=stats.get("insertions", 0),
+ deletions=stats.get("deletions", 0)
+ )
+ commits.append(commit_info)
+ except Exception as e:
+ self.logger.error(f"Error analyzing commits: {e}")
+
+ return commits
- def extract_documentation(self, file_path):
+ def extract_code_files(self, repo_path: Path, **filters) -> List[CodeFile]:
"""
- Extract documentation from code file.
+ Extract and process code files from repository.
- • Find and extract docstrings
- • Extract inline comments
- • Identify documentation blocks
- • Parse markdown documentation
- • Return documentation content
+ Args:
+ repo_path: Path to repository
+ **filters: File filtering criteria:
+ - extensions: List of allowed extensions
+ - languages: List of allowed languages
+ - exclude_patterns: Patterns to exclude
+ - max_size: Maximum file size
+
+ Returns:
+ list: Processed code files
"""
- pass
+ code_files = []
+
+ for file_path in repo_path.rglob('*'):
+ if not file_path.is_file():
+ continue
+
+ # Apply filters
+ if filters.get("extensions"):
+ if file_path.suffix not in filters["extensions"]:
+ continue
+
+ if filters.get("exclude_patterns"):
+ if any(re.match(pattern, str(file_path)) for pattern in filters["exclude_patterns"]):
+ continue
+
+ if filters.get("max_size"):
+ if file_path.stat().st_size > filters["max_size"]:
+ continue
+
+ # Skip common non-code files
+ if file_path.name in ['.gitignore', '.gitkeep', '.gitattributes']:
+ continue
+
+ if file_path.suffix in ['.pyc', '.pyo', '.pyd', '.so', '.dll']:
+ continue
+
+ try:
+ code_file = self.code_extractor.extract_file_content(file_path)
+
+ # Apply language filter
+ if filters.get("languages"):
+ if code_file.language not in filters["languages"]:
+ continue
+
+ code_files.append(code_file)
+ except Exception as e:
+ self.logger.debug(f"Failed to extract {file_path}: {e}")
+
+ return code_files
- def analyze_dependencies(self, file_path):
+ def get_repository_info(self, repo_url: str, repo: Optional[git.Repo] = None) -> Dict[str, Any]:
"""
- Analyze file dependencies and imports.
+ Get repository metadata and information.
- • Parse import statements
- • Identify external dependencies
- • Map internal file dependencies
- • Analyze dependency relationships
- • Return dependency analysis
+ Args:
+ repo_url: Repository URL
+ repo: Git repository object (optional)
+
+ Returns:
+ dict: Repository information
"""
- pass
+ info = {
+ "url": repo_url,
+ "branches": [],
+ "tags": [],
+ "remote_info": {}
+ }
+
+ if repo:
+ try:
+ info["branches"] = [branch.name for branch in repo.branches]
+ info["tags"] = [tag.name for tag in repo.tags]
+
+ # Get remote information
+ if repo.remotes:
+ remote = repo.remotes.origin
+ info["remote_info"] = {
+ "url": remote.url,
+ "name": remote.name
+ }
+
+ # Get latest commit
+ if repo.heads:
+ latest_commit = repo.head.commit
+ info["latest_commit"] = {
+ "hash": latest_commit.hexsha[:7],
+ "message": latest_commit.message.strip(),
+ "author": str(latest_commit.author),
+ "date": datetime.fromtimestamp(latest_commit.committed_date).isoformat()
+ }
+ except Exception as e:
+ self.logger.warning(f"Error getting repository info: {e}")
+
+ return info
+
+ def _get_temp_dir(self) -> str:
+ """Get or create temporary directory for cloning."""
+ if self.temp_dir is None:
+ self.temp_dir = tempfile.mkdtemp(prefix="semantica_repo_")
+ return self.temp_dir
+
+ def cleanup(self):
+ """Cleanup temporary repository files."""
+ if self.temp_dir and os.path.exists(self.temp_dir):
+ shutil.rmtree(self.temp_dir)
+ self.temp_dir = None
diff --git a/libs/semantica/ingest/stream_ingestor.py b/libs/semantica/ingest/stream_ingestor.py
index 9a639fa8..7ae31df9 100644
--- a/libs/semantica/ingest/stream_ingestor.py
+++ b/libs/semantica/ingest/stream_ingestor.py
@@ -17,239 +17,606 @@ Main Classes:
- StreamMonitor: Stream health monitoring
"""
+import json
+import threading
+import time
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Callable, Dict, List, Optional
-class StreamIngestor:
- """
- Real-time stream ingestion handler.
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class StreamMessage:
+ """Stream message representation."""
- Processes data streams from various sources with
- support for different streaming protocols.
+ content: Any
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ timestamp: datetime = field(default_factory=datetime.now)
+ source: str = ""
+ partition: Optional[int] = None
+ offset: Optional[int] = None
+
+
+class StreamProcessor:
+ """
+ Generic stream data processor.
- 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
+ Base class for processing data from various
+ streaming sources with common functionality.
"""
- def __init__(self, config=None, **kwargs):
+ def __init__(self, source_config: Dict[str, Any], **options):
"""
- Initialize stream ingestor.
+ Initialize stream processor.
Args:
- config: Stream ingestion configuration
- **kwargs: Additional configuration parameters
+ source_config: Source-specific configuration
+ **options: Processing options
"""
- # TODO: Initialize stream processors
- # TODO: Setup stream monitor
- # TODO: Configure connection pools
- # TODO: Setup error handling
- pass
+ self.logger = get_logger("stream_processor")
+ self.source_config = source_config
+ self.options = options
+ self.message_handler: Optional[Callable] = None
+ self.error_handler: Optional[Callable] = None
+ self.running: bool = False
+ self.thread: Optional[threading.Thread] = None
+ self._processed_count: int = 0
+ self._error_count: int = 0
- def ingest_kafka(self, topic, **options):
+ def process_message(self, message: Any) -> Dict[str, Any]:
"""
- Ingest data from Kafka topic.
+ Process individual stream message.
Args:
- topic: Kafka topic name
- **options: Processing options
+ message: Stream message to process
Returns:
- KafkaProcessor: Kafka stream processor
+ ProcessedData: Processed message data
"""
- # TODO: Initialize Kafka consumer
- # TODO: Configure topic subscription
- # TODO: Setup message processing
- # TODO: Return processor instance
- pass
+ try:
+ # Parse message content
+ if isinstance(message, bytes):
+ content = json.loads(message.decode('utf-8'))
+ elif isinstance(message, str):
+ content = json.loads(message)
+ elif isinstance(message, dict):
+ content = message
+ else:
+ content = {"raw": str(message)}
+
+ # Extract metadata
+ metadata = content.get("metadata", {})
+
+ # Apply transformations if configured
+ if self.options.get("transform"):
+ transform_fn = self.options["transform"]
+ content = transform_fn(content)
+
+ # Validate data if configured
+ if self.options.get("validate"):
+ validate_fn = self.options["validate"]
+ if not validate_fn(content):
+ raise ValidationError("Message validation failed")
+
+ self._processed_count += 1
+
+ return {
+ "content": content,
+ "metadata": metadata,
+ "processed_at": datetime.now().isoformat()
+ }
+
+ except Exception as e:
+ self._error_count += 1
+ self.logger.error(f"Failed to process message: {e}")
+
+ if self.error_handler:
+ self.error_handler(message, e)
+ else:
+ raise ProcessingError(f"Failed to process message: {e}")
+
+ def start_consuming(self):
+ """Start consuming from stream."""
+ if self.running:
+ self.logger.warning("Processor already running")
+ return
+
+ self.running = True
+ self.thread = threading.Thread(target=self._consume_loop, daemon=True)
+ self.thread.start()
+ self.logger.info("Stream processor started")
+
+ def stop_consuming(self):
+ """Stop consuming from stream."""
+ self.running = False
+ if self.thread:
+ self.thread.join(timeout=5)
+ self.logger.info("Stream processor stopped")
+
+ def set_message_handler(self, handler: Callable):
+ """Set message processing handler."""
+ self.message_handler = handler
+
+ def set_error_handler(self, handler: Callable):
+ """Set error handling function."""
+ self.error_handler = handler
- def ingest_pulsar(self, topic, **options):
+ def _consume_loop(self):
+ """Main consumption loop (to be overridden by subclasses)."""
+ while self.running:
+ try:
+ # This will be implemented by specific processors
+ time.sleep(0.1)
+ except Exception as e:
+ self.logger.error(f"Error in consumption loop: {e}")
+ if not self.running:
+ break
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Get processor statistics."""
+ return {
+ "processed": self._processed_count,
+ "errors": self._error_count,
+ "running": self.running
+ }
+
+
+class KafkaProcessor(StreamProcessor):
+ """Kafka stream processor."""
+
+ def __init__(self, topic: str, bootstrap_servers: List[str], **options):
"""
- Ingest data from Pulsar topic.
+ Initialize Kafka processor.
Args:
- topic: Pulsar topic name
+ topic: Kafka topic name
+ bootstrap_servers: List of Kafka broker addresses
**options: Processing options
-
- Returns:
- PulsarProcessor: Pulsar stream processor
"""
- # TODO: Initialize Pulsar consumer
- # TODO: Configure topic subscription
- # TODO: Setup message processing
- # TODO: Return processor instance
- pass
+ from kafka import KafkaConsumer
+
+ source_config = {
+ "type": "kafka",
+ "topic": topic,
+ "bootstrap_servers": bootstrap_servers
+ }
+ super().__init__(source_config, **options)
+
+ self.topic = topic
+ self.consumer = KafkaConsumer(
+ topic,
+ bootstrap_servers=bootstrap_servers,
+ value_deserializer=lambda m: json.loads(m.decode('utf-8')),
+ **options.get("consumer_config", {})
+ )
+
+ def _consume_loop(self):
+ """Kafka consumption loop."""
+ while self.running:
+ try:
+ message_pack = self.consumer.poll(timeout_ms=1000)
+ for topic_partition, messages in message_pack.items():
+ for message in messages:
+ processed = self.process_message(message.value)
+ if self.message_handler:
+ self.message_handler(processed)
+ except Exception as e:
+ self.logger.error(f"Error consuming from Kafka: {e}")
+ if not self.running:
+ break
+
+
+class RabbitMQProcessor(StreamProcessor):
+ """RabbitMQ stream processor."""
- def ingest_rabbitmq(self, queue, **options):
+ def __init__(self, queue: str, connection_url: str, **options):
"""
- Ingest data from RabbitMQ queue.
+ Initialize RabbitMQ processor.
Args:
queue: RabbitMQ queue name
+ connection_url: RabbitMQ connection URL
**options: Processing options
-
- Returns:
- RabbitMQProcessor: RabbitMQ stream processor
"""
- # TODO: Initialize RabbitMQ consumer
- # TODO: Configure queue binding
- # TODO: Setup message processing
- # TODO: Return processor instance
- pass
+ import pika
+
+ source_config = {
+ "type": "rabbitmq",
+ "queue": queue,
+ "connection_url": connection_url
+ }
+ super().__init__(source_config, **options)
+
+ self.queue = queue
+ self.connection = pika.BlockingConnection(pika.URLParameters(connection_url))
+ self.channel = self.connection.channel()
+ self.channel.queue_declare(queue=queue, durable=options.get("durable", True))
+
+ def _consume_loop(self):
+ """RabbitMQ consumption loop."""
+ def callback(ch, method, properties, body):
+ try:
+ processed = self.process_message(body)
+ if self.message_handler:
+ self.message_handler(processed)
+ ch.basic_ack(delivery_tag=method.delivery_tag)
+ except Exception as e:
+ self.logger.error(f"Error processing RabbitMQ message: {e}")
+ ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
+
+ self.channel.basic_consume(
+ queue=self.queue,
+ on_message_callback=callback
+ )
+
+ try:
+ while self.running:
+ self.connection.process_data_events(time_limit=1)
+ except Exception as e:
+ self.logger.error(f"Error in RabbitMQ consumption: {e}")
+ finally:
+ if self.channel:
+ self.channel.close()
+ if self.connection:
+ self.connection.close()
+
+
+class KinesisProcessor(StreamProcessor):
+ """AWS Kinesis stream processor."""
- def ingest_kinesis(self, stream_name, **options):
+ def __init__(self, stream_name: str, region: str, **options):
"""
- Ingest data from Kinesis stream.
+ Initialize Kinesis processor.
Args:
stream_name: Kinesis stream name
+ region: AWS region
**options: Processing options
-
- Returns:
- KinesisProcessor: Kinesis stream processor
"""
- # TODO: Initialize Kinesis consumer
- # TODO: Configure stream subscription
- # TODO: Setup record processing
- # TODO: Return processor instance
- pass
+ import boto3
+
+ source_config = {
+ "type": "kinesis",
+ "stream_name": stream_name,
+ "region": region
+ }
+ super().__init__(source_config, **options)
+
+ self.stream_name = stream_name
+ self.kinesis = boto3.client('kinesis', region_name=region)
+ self.shard_iterator = None
+
+ # Get shard iterator
+ response = self.kinesis.get_shard_iterator(
+ StreamName=stream_name,
+ ShardId=options.get("shard_id", "0"),
+ ShardIteratorType=options.get("shard_iterator_type", "LATEST")
+ )
+ self.shard_iterator = response['ShardIterator']
- def start_streaming(self, processors):
+ def _consume_loop(self):
+ """Kinesis consumption loop."""
+ while self.running:
+ try:
+ response = self.kinesis.get_records(ShardIterator=self.shard_iterator)
+
+ for record in response['Records']:
+ processed = self.process_message(record['Data'])
+ if self.message_handler:
+ self.message_handler(processed)
+
+ self.shard_iterator = response['NextShardIterator']
+ time.sleep(1) # Avoid throttling
+
+ except Exception as e:
+ self.logger.error(f"Error consuming from Kinesis: {e}")
+ if not self.running:
+ break
+ time.sleep(5)
+
+
+class PulsarProcessor(StreamProcessor):
+ """Apache Pulsar stream processor."""
+
+ def __init__(self, topic: str, service_url: str, **options):
"""
- Start processing multiple streams.
+ Initialize Pulsar processor.
Args:
- processors: List of stream processors
+ topic: Pulsar topic name
+ service_url: Pulsar service URL
+ **options: Processing options
"""
- # TODO: Start all processors
- # TODO: Setup coordination
- # TODO: Handle failures
- # TODO: Monitor performance
- pass
+ import pulsar
+
+ source_config = {
+ "type": "pulsar",
+ "topic": topic,
+ "service_url": service_url
+ }
+ super().__init__(source_config, **options)
+
+ self.topic = topic
+ self.client = pulsar.Client(service_url)
+ self.consumer = self.client.subscribe(
+ topic,
+ subscription_name=options.get("subscription_name", "semantica-consumer"),
+ consumer_type=pulsar.ConsumerType.Shared
+ )
+
+ def _consume_loop(self):
+ """Pulsar consumption loop."""
+ while self.running:
+ try:
+ msg = self.consumer.receive(timeout_millis=1000)
+ try:
+ processed = self.process_message(msg.data())
+ if self.message_handler:
+ self.message_handler(processed)
+ self.consumer.acknowledge(msg)
+ except Exception as e:
+ self.logger.error(f"Error processing Pulsar message: {e}")
+ self.consumer.negative_acknowledge(msg)
+ except Exception as e:
+ if "timeout" not in str(e).lower():
+ self.logger.error(f"Error consuming from Pulsar: {e}")
+ if not self.running:
+ break
-class StreamProcessor:
+class StreamMonitor:
"""
- Generic stream data processor.
+ Stream health and performance monitoring.
- Base class for processing data from various
- streaming sources with common functionality.
+ Monitors stream processing health, performance
+ metrics, and error rates.
"""
- def __init__(self, source_config, **options):
+ def __init__(self, **config):
"""
- Initialize stream processor.
+ Initialize stream monitor.
Args:
- source_config: Source-specific configuration
- **options: Processing options
+ **config: Monitor configuration
"""
- # TODO: Initialize source connection
- # TODO: Setup message handlers
- # TODO: Configure processing pipeline
- # TODO: Setup error handling
- pass
+ self.logger = get_logger("stream_monitor")
+ self.config = config
+ self.processors: Dict[str, StreamProcessor] = {}
+ self.metrics: Dict[str, Dict[str, Any]] = {}
+ self.alert_thresholds = config.get("alert_thresholds", {
+ "error_rate": 0.1, # 10% error rate
+ "max_lag": 1000 # Maximum message lag
+ })
- def process_message(self, message):
+ def monitor_processor(self, processor: StreamProcessor, name: str = None):
"""
- Process individual stream message.
+ Monitor specific stream processor.
Args:
- message: Stream message to process
-
- Returns:
- ProcessedData: Processed message data
+ processor: Stream processor to monitor
+ name: Processor name (optional)
"""
- # TODO: Parse message content
- # TODO: Apply transformations
- # TODO: Extract metadata
- # TODO: Validate data
- # TODO: Return processed data
- pass
+ if name is None:
+ name = processor.source_config.get("type", "unknown")
+
+ self.processors[name] = processor
+ self.metrics[name] = {
+ "last_check": datetime.now(),
+ "processed": 0,
+ "errors": 0,
+ "healthy": True
+ }
+ self.logger.info(f"Started monitoring processor: {name}")
- def start_consuming(self):
+ def get_metrics(self, processor_name: Optional[str] = None) -> Dict[str, Any]:
"""
- Start consuming from stream.
+ Get monitoring metrics.
+
+ Args:
+ processor_name: Specific processor name
+
+ Returns:
+ dict: Monitoring metrics
"""
- # TODO: Start consumption loop
- # TODO: Process messages
- # TODO: Handle errors
- # TODO: Update metrics
- pass
+ if processor_name:
+ if processor_name not in self.processors:
+ return {}
+ processor = self.processors[processor_name]
+ stats = processor.get_stats()
+ return {
+ processor_name: {
+ **self.metrics.get(processor_name, {}),
+ **stats
+ }
+ }
+ else:
+ # Return all metrics
+ all_metrics = {}
+ for name, processor in self.processors.items():
+ stats = processor.get_stats()
+ all_metrics[name] = {
+ **self.metrics.get(name, {}),
+ **stats
+ }
+ return all_metrics
- def stop_consuming(self):
+ def check_health(self) -> Dict[str, Any]:
"""
- Stop consuming from stream.
+ Check overall stream health.
+
+ Returns:
+ dict: Health status
"""
- # TODO: Stop consumption loop
- # TODO: Cleanup resources
- # TODO: Save state
- pass
+ health_status = {
+ "overall": "healthy",
+ "processors": {},
+ "timestamp": datetime.now().isoformat()
+ }
+
+ unhealthy_count = 0
+
+ for name, processor in self.processors.items():
+ stats = processor.get_stats()
+ metrics = self.metrics.get(name, {})
+
+ # Calculate error rate
+ total = stats.get("processed", 0) + stats.get("errors", 0)
+ error_rate = stats.get("errors", 0) / total if total > 0 else 0
+
+ is_healthy = (
+ processor.running and
+ error_rate < self.alert_thresholds["error_rate"]
+ )
+
+ if not is_healthy:
+ unhealthy_count += 1
+
+ health_status["processors"][name] = {
+ "healthy": is_healthy,
+ "running": processor.running,
+ "error_rate": error_rate,
+ "processed": stats.get("processed", 0),
+ "errors": stats.get("errors", 0)
+ }
+
+ if unhealthy_count > 0:
+ health_status["overall"] = "unhealthy" if unhealthy_count == len(self.processors) else "degraded"
+
+ return health_status
-class StreamMonitor:
+class StreamIngestor:
"""
- Stream health and performance monitoring.
+ Real-time stream ingestion handler.
- Monitors stream processing health, performance
- metrics, and error rates.
+ 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
"""
- def __init__(self, **config):
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
- Initialize stream monitor.
+ Initialize stream ingestor.
Args:
- **config: Monitor configuration
+ config: Stream ingestion configuration
+ **kwargs: Additional configuration parameters
"""
- # TODO: Setup metrics collection
- # TODO: Initialize alerting
- # TODO: Configure thresholds
- # TODO: Setup reporting
- pass
+ self.logger = get_logger("stream_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize stream processors dictionary
+ self.processors: Dict[str, StreamProcessor] = {}
+
+ # Setup stream monitor
+ self.monitor = StreamMonitor(**self.config)
- def monitor_processor(self, processor):
+ def ingest_kafka(self, topic: str, bootstrap_servers: List[str], **options) -> KafkaProcessor:
"""
- Monitor specific stream processor.
+ Ingest data from Kafka topic.
Args:
- processor: Stream processor to monitor
+ topic: Kafka topic name
+ bootstrap_servers: List of Kafka broker addresses
+ **options: Processing options
+
+ Returns:
+ KafkaProcessor: Kafka stream processor
"""
- # TODO: Track processor metrics
- # TODO: Monitor error rates
- # TODO: Check performance
- # TODO: Generate alerts
- pass
+ processor = KafkaProcessor(topic, bootstrap_servers, **options)
+ self.processors[f"kafka_{topic}"] = processor
+ self.monitor.monitor_processor(processor, f"kafka_{topic}")
+ return processor
- def get_metrics(self, processor_name=None):
+ def ingest_pulsar(self, topic: str, service_url: str, **options) -> PulsarProcessor:
"""
- Get monitoring metrics.
+ Ingest data from Pulsar topic.
Args:
- processor_name: Specific processor name
+ topic: Pulsar topic name
+ service_url: Pulsar service URL
+ **options: Processing options
Returns:
- dict: Monitoring metrics
+ PulsarProcessor: Pulsar stream processor
"""
- # TODO: Collect metrics
- # TODO: Aggregate data
- # TODO: Return metrics dict
- pass
+ processor = PulsarProcessor(topic, service_url, **options)
+ self.processors[f"pulsar_{topic}"] = processor
+ self.monitor.monitor_processor(processor, f"pulsar_{topic}")
+ return processor
- def check_health(self):
+ def ingest_rabbitmq(self, queue: str, connection_url: str, **options) -> RabbitMQProcessor:
"""
- Check overall stream health.
+ Ingest data from RabbitMQ queue.
+ Args:
+ queue: RabbitMQ queue name
+ connection_url: RabbitMQ connection URL
+ **options: Processing options
+
Returns:
- dict: Health status
+ RabbitMQProcessor: RabbitMQ stream processor
"""
- # TODO: Check all processors
- # TODO: Evaluate health status
- # TODO: Return health report
- pass
+ processor = RabbitMQProcessor(queue, connection_url, **options)
+ self.processors[f"rabbitmq_{queue}"] = processor
+ self.monitor.monitor_processor(processor, f"rabbitmq_{queue}")
+ return processor
+
+ def ingest_kinesis(self, stream_name: str, region: str, **options) -> KinesisProcessor:
+ """
+ Ingest data from Kinesis stream.
+
+ Args:
+ stream_name: Kinesis stream name
+ region: AWS region
+ **options: Processing options
+
+ Returns:
+ KinesisProcessor: Kinesis stream processor
+ """
+ processor = KinesisProcessor(stream_name, region, **options)
+ self.processors[f"kinesis_{stream_name}"] = processor
+ self.monitor.monitor_processor(processor, f"kinesis_{stream_name}")
+ return processor
+
+ def start_streaming(self, processors: Optional[List[StreamProcessor]] = None):
+ """
+ Start processing multiple streams.
+
+ Args:
+ processors: List of stream processors (if None, starts all)
+ """
+ if processors is None:
+ processors = list(self.processors.values())
+
+ for processor in processors:
+ try:
+ processor.start_consuming()
+ self.logger.info(f"Started stream processor: {processor.source_config.get('type')}")
+ except Exception as e:
+ self.logger.error(f"Failed to start processor: {e}")
+ raise ProcessingError(f"Failed to start stream processor: {e}")
+
+ def stop_streaming(self):
+ """Stop all stream processors."""
+ for name, processor in self.processors.items():
+ try:
+ processor.stop_consuming()
+ self.logger.info(f"Stopped stream processor: {name}")
+ except Exception as e:
+ self.logger.error(f"Error stopping processor {name}: {e}")
diff --git a/libs/semantica/ingest/web_ingestor.py b/libs/semantica/ingest/web_ingestor.py
index fd218d80..7e3d34ea 100644
--- a/libs/semantica/ingest/web_ingestor.py
+++ b/libs/semantica/ingest/web_ingestor.py
@@ -17,119 +17,219 @@ Main Classes:
- ContentExtractor: Web content extraction
"""
+import time
+import re
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Set
+from urllib.parse import urljoin, urlparse
+from urllib.robotparser import RobotFileParser
-class WebIngestor:
- """
- Web content ingestion handler.
+import requests
+from bs4 import BeautifulSoup
+from requests.adapters import HTTPAdapter
+from urllib3.util.retry import Retry
+
+from ..utils.exceptions import ProcessingError, ValidationError
+from ..utils.logging import get_logger
+
+
+@dataclass
+class WebContent:
+ """Web content representation."""
- Fetches and processes content from websites with support
- for various protocols and content types.
+ url: str
+ title: str = ""
+ text: str = ""
+ html: str = ""
+ metadata: Dict[str, Any] = field(default_factory=dict)
+ links: List[str] = field(default_factory=list)
+ fetched_at: datetime = field(default_factory=datetime.now)
+ status_code: Optional[int] = None
+
+
+class RateLimiter:
+ """Simple rate limiter for web requests."""
- Attributes:
- session: HTTP session for requests
- rate_limiter: Rate limiting controller
- content_extractor: Content extraction engine
- robots_checker: Robots.txt compliance checker
+ def __init__(self, delay: float = 1.0):
+ """
+ Initialize rate limiter.
- Methods:
- ingest_url(): Ingest single URL
- crawl_sitemap(): Crawl sitemap
- crawl_domain(): Crawl entire domain
- extract_content(): Extract content from page
- """
+ Args:
+ delay: Delay between requests in seconds
+ """
+ self.delay = delay
+ self.last_request_time: float = 0.0
- def __init__(self, config=None, **kwargs):
+ def wait_if_needed(self):
+ """Wait if necessary to respect rate limit."""
+ elapsed = time.time() - self.last_request_time
+ if elapsed < self.delay:
+ time.sleep(self.delay - elapsed)
+ self.last_request_time = time.time()
+
+
+class RobotsChecker:
+ """Robots.txt compliance checker."""
+
+ def __init__(self, user_agent: str = "SemanticaBot/1.0"):
"""
- Initialize web ingestor.
+ Initialize robots checker.
Args:
- config: Web ingestion configuration
- **kwargs: Additional configuration parameters
+ user_agent: User agent string
"""
- # TODO: Initialize HTTP session
- # TODO: Setup rate limiting
- # TODO: Initialize content extractor
- # TODO: Setup robots checker
- # TODO: Configure user agent
- pass
+ self.user_agent = user_agent
+ self.parsers: Dict[str, RobotFileParser] = {}
- def ingest_url(self, url, **options):
+ def can_fetch(self, url: str) -> bool:
"""
- Ingest content from a single URL.
+ Check if URL can be fetched according to robots.txt.
Args:
- url: URL to ingest
- **options: Processing options
+ url: URL to check
Returns:
- WebContent: Extracted web content
+ bool: True if can fetch, False otherwise
"""
- # TODO: Validate URL
- # TODO: Check robots.txt
- # TODO: Apply rate limiting
- # TODO: Fetch content
- # TODO: Extract content
- # TODO: Return web content object
- pass
+ parsed = urlparse(url)
+ domain = f"{parsed.scheme}://{parsed.netloc}"
+
+ if domain not in self.parsers:
+ # Create robots.txt URL
+ robots_url = urljoin(domain, "/robots.txt")
+
+ # Create parser
+ parser = RobotFileParser()
+ parser.set_url(robots_url)
+
+ try:
+ parser.read()
+ except Exception:
+ # If robots.txt not available, assume allowed
+ pass
+
+ self.parsers[domain] = parser
+
+ parser = self.parsers[domain]
+ return parser.can_fetch(self.user_agent, url)
+
+
+class ContentExtractor:
+ """
+ Web content extraction and cleaning.
+
+ Extracts text, metadata, and structured data from
+ web pages with various extraction strategies.
+ """
- def crawl_sitemap(self, sitemap_url, **filters):
+ def __init__(self, **config):
"""
- Crawl URLs from sitemap.
+ Initialize content extractor.
Args:
- sitemap_url: URL of sitemap
- **filters: URL filtering criteria
+ **config: Extraction configuration
+ """
+ self.logger = get_logger("content_extractor")
+ self.config = config
+
+ def extract_text(self, html_content: str) -> str:
+ """
+ Extract clean text from HTML.
+
+ Args:
+ html_content: HTML content
Returns:
- list: List of web content objects
+ str: Extracted text content
"""
- # TODO: Fetch sitemap
- # TODO: Parse sitemap XML
- # TODO: Extract URLs
- # TODO: Apply filters
- # TODO: Process each URL
- # TODO: Return content list
- pass
+ soup = BeautifulSoup(html_content, 'html.parser')
+
+ # Remove script and style elements
+ for element in soup(['script', 'style']):
+ element.decompose()
+
+ # Extract text
+ text = soup.get_text()
+
+ # Clean whitespace
+ 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 crawl_domain(self, domain, max_pages=100, **options):
+ def extract_metadata(self, html_content: str, url: Optional[str] = None) -> Dict[str, Any]:
"""
- Crawl entire domain starting from root.
+ Extract metadata from HTML.
Args:
- domain: Domain to crawl
- max_pages: Maximum pages to crawl
- **options: Crawling options
+ html_content: HTML content
+ url: Source URL
Returns:
- list: List of web content objects
+ dict: Extracted metadata
"""
- # TODO: Start from domain root
- # TODO: Discover links
- # TODO: Apply crawling rules
- # TODO: Respect robots.txt
- # TODO: Apply rate limiting
- # TODO: Process discovered pages
- # TODO: Return content list
- pass
+ metadata = {'url': url} if url else {}
+
+ soup = BeautifulSoup(html_content, 'html.parser')
+
+ # Extract title
+ title_tag = soup.find('title')
+ if title_tag:
+ metadata['title'] = title_tag.get_text().strip()
+
+ # Extract 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
+ og_data = {}
+ for meta_tag in soup.find_all('meta', property=re.compile(r'^og:')):
+ property_name = meta_tag.get('property', '').replace('og:', '')
+ content = meta_tag.get('content')
+ if property_name and content:
+ og_data[property_name] = content
+
+ if og_data:
+ metadata['og'] = og_data
+
+ return metadata
- def extract_content(self, html_content, url=None):
+ def extract_links(self, html_content: str, base_url: Optional[str] = None) -> List[str]:
"""
- Extract content from HTML.
+ Extract links from HTML.
Args:
- html_content: HTML content to extract from
- url: Source URL for context
+ html_content: HTML content
+ base_url: Base URL for relative links
Returns:
- WebContent: Extracted content
+ list: List of extracted links
"""
- # TODO: Parse HTML
- # TODO: Extract text content
- # TODO: Extract metadata
- # TODO: Extract links
- # TODO: Clean content
- # TODO: Return web content
- pass
+ links = []
+
+ soup = BeautifulSoup(html_content, 'html.parser')
+
+ for link_tag in soup.find_all('a', href=True):
+ href = link_tag['href']
+
+ # Resolve relative URLs
+ if base_url:
+ link = urljoin(base_url, href)
+ else:
+ link = href
+
+ # Filter valid links
+ parsed = urlparse(link)
+ if parsed.scheme in ('http', 'https'):
+ links.append(link)
+
+ return links
class SitemapCrawler:
@@ -147,13 +247,10 @@ class SitemapCrawler:
Args:
**config: Crawler configuration
"""
- # TODO: Initialize XML parser
- # TODO: Setup URL validation
- # TODO: Configure crawling rules
- # TODO: Setup progress tracking
- pass
+ self.logger = get_logger("sitemap_crawler")
+ self.config = config
- def parse_sitemap(self, sitemap_url):
+ def parse_sitemap(self, sitemap_url: str) -> List[str]:
"""
Parse sitemap and extract URLs.
@@ -163,14 +260,39 @@ class SitemapCrawler:
Returns:
list: List of URLs from sitemap
"""
- # TODO: Fetch sitemap
- # TODO: Parse XML content
- # TODO: Extract URL entries
- # TODO: Validate URLs
- # TODO: Return URL list
- pass
+ try:
+ response = requests.get(sitemap_url, timeout=30)
+ response.raise_for_status()
+
+ root = ET.fromstring(response.content)
+
+ # Namespace handling
+ namespaces = {
+ 'sitemap': 'http://www.sitemaps.org/schemas/sitemap/0.9'
+ }
+
+ urls = []
+
+ # Extract URLs from urlset
+ 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
+ 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())
+
+ 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}")
- def crawl_sitemap_index(self, index_url):
+ def crawl_sitemap_index(self, index_url: str) -> List[str]:
"""
Crawl sitemap index and all referenced sitemaps.
@@ -180,83 +302,304 @@ class SitemapCrawler:
Returns:
list: List of all URLs from all sitemaps
"""
- # TODO: Parse sitemap index
- # TODO: Get referenced sitemaps
- # TODO: Parse each sitemap
- # TODO: Collect all URLs
- # TODO: Return combined URL list
- pass
+ try:
+ response = requests.get(index_url, timeout=30)
+ response.raise_for_status()
+
+ root = ET.fromstring(response.content)
+
+ # Namespace handling
+ namespaces = {
+ 'sitemap': 'http://www.sitemaps.org/schemas/sitemap/0.9'
+ }
+
+ all_urls = []
+
+ # Find sitemap references
+ 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
+ urls = self.parse_sitemap(sitemap_url)
+ all_urls.extend(urls)
+
+ # Also handle non-namespaced sitemaps
+ if not all_urls:
+ for sitemap_elem in root.findall('.//sitemap'):
+ loc_elem = sitemap_elem.find('loc')
+ if loc_elem is not None and loc_elem.text:
+ sitemap_url = loc_elem.text.strip()
+ urls = self.parse_sitemap(sitemap_url)
+ all_urls.extend(urls)
+
+ 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}")
-class ContentExtractor:
+class WebIngestor:
"""
- Web content extraction and cleaning.
+ Web content ingestion handler.
- Extracts text, metadata, and structured data from
- web pages with various extraction strategies.
+ Fetches and processes content from websites with support
+ for various protocols and content types.
+
+ 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
"""
- def __init__(self, **config):
+ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):
"""
- Initialize content extractor.
+ Initialize web ingestor.
Args:
- **config: Extraction configuration
+ config: Web ingestion configuration
+ **kwargs: Additional configuration parameters
"""
- # TODO: Initialize HTML parser
- # TODO: Setup text extractors
- # TODO: Configure metadata extractors
- # TODO: Setup content cleaners
- pass
+ self.logger = get_logger("web_ingestor")
+ self.config = config or {}
+ self.config.update(kwargs)
+
+ # Initialize HTTP session
+ self.session = requests.Session()
+
+ # Configure user agent
+ user_agent = self.config.get('user_agent', 'SemanticaBot/1.0')
+ self.session.headers.update({'User-Agent': user_agent})
+
+ # Setup retry strategy
+ 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],
+ )
+ 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)
+ if respect_robots:
+ self.robots_checker = RobotsChecker(user_agent=user_agent)
+ else:
+ self.robots_checker = None
- def extract_text(self, html_content):
+ def ingest_url(self, url: str, **options) -> WebContent:
"""
- Extract clean text from HTML.
+ Ingest content from a single URL.
Args:
- html_content: HTML content
+ url: URL to ingest
+ **options: Processing options
Returns:
- str: Extracted text content
+ WebContent: Extracted web content
"""
- # TODO: Parse HTML
- # TODO: Remove script/style tags
- # TODO: Extract text content
- # TODO: Clean whitespace
- # TODO: Return clean text
- pass
+ # Validate URL
+ try:
+ parsed = urlparse(url)
+ if not parsed.scheme or not parsed.netloc:
+ raise ValidationError(f"Invalid URL: {url}")
+ except Exception as e:
+ raise ValidationError(f"Invalid URL: {url}") from e
+
+ # Check robots.txt
+ 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
+ self.rate_limiter.wait_if_needed()
+
+ # Fetch content
+ try:
+ timeout = options.get('timeout', self.config.get('timeout', 30))
+ response = self.session.get(url, timeout=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}")
+
+ # Extract content
+ html_content = response.text
+ web_content = self.extract_content(html_content, url=url)
+ web_content.status_code = response.status_code
+
+ return web_content
- def extract_metadata(self, html_content, url=None):
+ def crawl_sitemap(self, sitemap_url: str, **filters) -> List[WebContent]:
"""
- Extract metadata from HTML.
+ Crawl URLs from sitemap.
Args:
- html_content: HTML content
- url: Source URL
+ sitemap_url: URL of sitemap
+ **filters: URL filtering criteria
Returns:
- dict: Extracted metadata
+ list: List of web content objects
"""
- # TODO: Extract title
- # TODO: Extract meta tags
- # TODO: Extract Open Graph data
- # TODO: Extract structured data
- # TODO: Return metadata dict
- pass
+ crawler = SitemapCrawler(**self.config)
+
+ # Parse sitemap
+ try:
+ urls = crawler.parse_sitemap(sitemap_url)
+ except Exception as e:
+ # Try as sitemap index
+ try:
+ urls = crawler.crawl_sitemap_index(sitemap_url)
+ except Exception:
+ raise ProcessingError(f"Failed to parse sitemap: {e}")
+
+ # Apply filters
+ if filters:
+ urls = self._apply_url_filters(urls, filters)
+
+ # Process each URL
+ web_contents = []
+ max_urls = filters.get('max_urls', self.config.get('max_urls'))
+
+ for idx, url in enumerate(urls):
+ if max_urls and idx >= max_urls:
+ break
+
+ try:
+ web_content = self.ingest_url(url)
+ web_contents.append(web_content)
+ self.logger.debug(f"Crawled URL {idx+1}/{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}")
+
+ return web_contents
- def extract_links(self, html_content, base_url=None):
+ def crawl_domain(self, domain: str, max_pages: int = 100, **options) -> List[WebContent]:
"""
- Extract links from HTML.
+ Crawl entire domain starting from root.
Args:
- html_content: HTML content
- base_url: Base URL for relative links
+ domain: Domain to crawl
+ max_pages: Maximum pages to crawl
+ **options: Crawling options
Returns:
- list: List of extracted links
+ list: List of web content objects
+ """
+ # Normalize domain
+ if not domain.startswith(('http://', 'https://')):
+ domain = f"https://{domain}"
+
+ # Start from domain root
+ visited: Set[str] = set()
+ to_visit: List[str] = [domain]
+ web_contents = []
+
+ while to_visit and len(web_contents) < max_pages:
+ url = to_visit.pop(0)
+
+ if url in visited:
+ continue
+
+ visited.add(url)
+
+ try:
+ web_content = self.ingest_url(url)
+ web_contents.append(web_content)
+
+ # Discover links
+ 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:
+ to_visit.append(link)
+
+ self.logger.debug(f"Crawled page {len(web_contents)}/{max_pages}: {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}")
+
+ return web_contents
+
+ def extract_content(self, html_content: str, url: Optional[str] = None) -> WebContent:
"""
- # TODO: Find all link tags
- # TODO: Resolve relative URLs
- # TODO: Filter valid links
- # TODO: Return link list
- pass
+ Extract content from HTML.
+
+ Args:
+ html_content: HTML content to extract from
+ url: Source URL for context
+
+ Returns:
+ WebContent: Extracted content
+ """
+ # Extract text content
+ text = self.content_extractor.extract_text(html_content)
+
+ # Extract metadata
+ metadata = self.content_extractor.extract_metadata(html_content, url=url)
+
+ # Extract links
+ links = self.content_extractor.extract_links(html_content, base_url=url)
+
+ # Get title
+ title = metadata.get('title', '')
+
+ # Create web content object
+ web_content = WebContent(
+ url=url or '',
+ title=title,
+ text=text,
+ html=html_content,
+ metadata=metadata,
+ links=links
+ )
+
+ return web_content
+
+ def _apply_url_filters(self, urls: List[str], filters: Dict[str, Any]) -> List[str]:
+ """Apply filters to URL list."""
+ filtered = urls
+
+ if 'pattern' in filters:
+ pattern = filters['pattern']
+ import re
+ regex = re.compile(pattern)
+ filtered = [url for url in filtered if regex.search(url)]
+
+ if 'domains' in filters:
+ allowed_domains = filters['domains']
+ filtered = [
+ url for url in filtered
+ if any(domain in url for domain in allowed_domains)
+ ]
+
+ if 'exclude_pattern' in filters:
+ pattern = filters['exclude_pattern']
+ import re
+ regex = re.compile(pattern)
+ filtered = [url for url in filtered if not regex.search(url)]
+
+ return filtered