Saltar a contenido

Arquitectura de Capas - Hexagonal Architecture

Descripción

Diagrama de capas siguiendo Clean Architecture / Hexagonal Architecture (Ports & Adapters). Muestra la separación entre capas de dominio, aplicación, infraestructura e interfaces.

Las dependencias fluyen hacia adentro: Infrastructure → Application → Domain.

Diagrama

graph TB
    subgraph InterfacesLayer["Interfaces Layer (UI)"]
        GUI[Streamlit GUI<br/>app.py]
        CLI[CLI Interface<br/>cli.py<br/>✅ 20 comandos]
    end

    subgraph ApplicationLayer["Application Layer"]
        UC[Use Cases<br/>ProcessDocumentUseCase<br/>ExportExcelUseCase<br/>ImportExcelUseCase]
        DTOs[DTOs<br/>ProcessDocumentRequest<br/>ProcessDocumentResponse]
        Container[Service Container<br/>Dependency Injection]
    end

    subgraph DomainLayer["Domain Layer (Core)"]
        Entities[Entities<br/>Document<br/>DocumentType<br/>DocumentStatus]
        ValueObjects[Value Objects<br/>EntityResult<br/>OCRResult<br/>DuplicateCandidate]
    end

    subgraph InfrastructureLayer["Infrastructure Layer (Adapters)"]
        subgraph "OCR Adapters"
            OCRRouter[OCR Router<br/>Confidence-based]
            Tesseract[Tesseract Adapter]
            Paddle[PaddleOCR Adapter]
            QAnalyzer[Quality Analyzer]
        end

        subgraph "NER Adapters"
            SpaCy[SpaCy Adapter<br/>es_core_news_lg]
            CtxScorer[ContextScorer ✅]
            EntLinker[EntityLinker ✅]
            RadVal[RadicadoValidator ✅]
            StructAnalyzer[DocumentStructureAnalyzer ✅]
            NERensemble[EntityExtractorEnsemble ✅]
            ActiveLearn[ActiveLearning ✅<br/>Infraestructura]
            ActaReparto[ActaRepartoExtractor ✅]
            SectionsDet[SectionsDetector ✅]
            ProvMeasure[ProvisionalMeasureDetector ✅]
        end

        subgraph "Duplicate Detection"
            DedupEnsemble[Hybrid Ensemble<br/>Detector]
            ExactHash[Exact Matcher<br/>SHA-256]
            MinHash[MinHash LSH<br/>Matcher]
            TFIDF[TF-IDF Similarity<br/>Matcher]
            EntityMatch[Entity Matcher<br/>Legal Parties]
        end

        subgraph "Persistence"
            Repo[SQLite Repository<br/>FTS5 Support<br/>3 Mixins: Connection,<br/>Correction, Metrics]
            ISP[ISP Protocols:<br/>DocumentReader,<br/>DocumentWriter,<br/>DocumentSearcher,<br/>CorrectionRepository,<br/>MetricsRepository]
        end

        subgraph "Logging"
            Logger[Logger Service<br/>File + DB handlers]
            DBHandler[Database Handler<br/>Audit Trail]
        end
    end

    subgraph PortsLayer["Ports (Protocols/Interfaces)"]
        OCRPort[OCRPort Protocol]
        NERPort[NER Port Protocol]
        DedupPort[DuplicateDetectorPort]
        RepoPort[DocumentRepository<br/>Protocol ISP:<br/>Reader, Writer, Searcher,<br/>Correction, Metrics]
    end

    GUI --> Container
    CLI --> Container
    Container --> UC
    UC --> DTOs
    UC --> OCRPort
    UC --> NERPort
    UC --> DedupPort
    UC --> RepoPort

    DTOs --> Entities
    DTOs --> ValueObjects

    OCRPort -.implements.-> OCRRouter
    OCRRouter --> Tesseract
    OCRRouter --> Paddle
    OCRRouter --> QAnalyzer

    NERPort -.implements.-> SpaCy
    SpaCy --> CtxScorer
    SpaCy --> EntLinker
    SpaCy --> RadVal
    SpaCy --> StructAnalyzer
    NERPort -.implements.-> NERensemble
    SpaCy --> ActiveLearn
    SpaCy --> ActaReparto
    SpaCy --> SectionsDet
    SpaCy --> ProvMeasure

    DedupPort -.implements.-> DedupEnsemble
    DedupEnsemble --> ExactHash
    DedupEnsemble --> MinHash
    DedupEnsemble --> TFIDF
    DedupEnsemble --> EntityMatch

    RepoPort -.implements.-> ISP
    ISP -.implements.-> Repo

    OCRRouter -.logs.-> Logger
    SpaCy -.logs.-> Logger
    DedupEnsemble -.logs.-> Logger
    Logger --> DBHandler
    DBHandler --> Repo

    style DomainLayer fill:#d4f1d4
    style ApplicationLayer fill:#d4e4f7
    style InfrastructureLayer fill:#fff4d4
    style InterfacesLayer fill:#f7d4e4
    style PortsLayer fill:#e4d4f7

Descripción de Capas

1. Domain Layer (Núcleo)

Responsabilidad: Lógica de negocio pura, sin dependencias externas.

  • Entities: Document, DocumentType, DocumentStatus
  • Value Objects: EntityResult, OCRResult, DuplicateCandidate
  • Reglas de negocio: Validaciones de estado, invariantes del dominio

Característica clave: Cero dependencias a frameworks o bibliotecas externas.

2. Application Layer

Responsabilidad: Orquestación de casos de uso, coordinación entre puertos.

  • Use Cases: ProcessDocumentUseCase (pipeline OCR -> NER -> Dedup -> Persist), ExportExcelUseCase, ImportExcelUseCase
  • DTOs: Objetos inmutables para transferencia entre capas
  • Service Container: Inyección de dependencias, lazy loading de recursos

Pattern: Railway-Oriented Programming con returns.Result para manejo de errores.

3. Infrastructure Layer (Adapters)

Responsabilidad: Implementaciones concretas de puertos, integraciones externas.

  • OCR Adapters: Tesseract, PaddleOCR con routing inteligente
  • NER Adapters: SpaCy con modelo es_core_news_lg + Validators (ContextScorer, EntityLinker, RadicadoValidator, DocumentStructureAnalyzer) + Extractores especializados (ActaRepartoExtractor, SectionsDetector, ProvisionalMeasureDetector)
  • Duplicate Detection: 4 niveles (Exact, MinHash, TF-IDF, Entity)
  • Persistence: SQLite con FTS5 para búsqueda full-text, refactorizado en 3 mixins (Connection, Correction, Metrics)
  • Logging: Sistema centralizado con handlers de archivo (rotación diaria) y base de datos (auditoría)
  • Config Persistence: EnsembleConfig con save/load JSON (data/config/dedup_config.json)

Pattern: Adapter Pattern, cada implementación cumple un Port (protocolo ABC).

4. Interfaces Layer

Responsabilidad: Interacción con usuarios (GUI, CLI).

  • Streamlit GUI ✅: Interfaz web para operadores (9 páginas implementadas)
  • CLI ✅: Interfaz de línea de comandos con 20 comandos (procesamiento batch, búsqueda, exportación, debugging) en interfaces/cli.py

5. Ports (Protocolos)

Responsabilidad: Contratos (interfaces) que define Application, implementa Infrastructure.

  • OCRPort: Contrato para motores OCR
  • NERPort: Contrato para extractores de entidades
  • DuplicateDetectorPort: Contrato para detectores de duplicados
  • DocumentRepository: Contrato para persistencia, segregado en ISP protocols: DocumentReader, DocumentWriter, DocumentSearcher, CorrectionRepository, MetricsRepository

Flujo de Dependencias

GUI/CLI → Application → Ports ← Infrastructure
            Domain (Core)

Regla de Oro: Las capas internas nunca conocen las externas. Infrastructure depende de Application, pero no al revés.

Principios Aplicados

  • Dependency Inversion Principle (DIP): Application depende de abstracciones (Ports), no implementaciones.
  • Single Responsibility Principle (SRP): Cada adapter tiene una responsabilidad única.
  • Open/Closed Principle (OCP): Extender con nuevos adapters sin modificar Application.
  • Interface Segregation Principle (ISP): Ports mínimos, específicos por caso de uso.

Leyenda de Estados

Símbolo Significado
Implementado y funcional
Planificado para fase futura
🔬 En investigación

Última actualización: 2026-03-05 (CLI implementado, NER extractores, ISP protocols, use cases import/export)