Find a file
2025-12-31 09:54:16 +00:00
.vscode chore: add tests for worker class 2024-04-23 10:24:48 +00:00
integration feat!: configurable bucket names, renamed MINIO_ to S3_ 2025-12-22 12:57:05 +01:00
kimiworker chore(release): 8.0.4 2025-12-31 09:51:46 +00:00
.editorconfig chore: set .editorconfig 2025-04-21 23:19:51 +00:00
.gitignore feat: add very basic test setup 2023-09-26 15:22:11 +02:00
.gitlab-ci.yml chore: set python version for ci job 2025-12-29 17:16:23 +01:00
.python-version fix(deps): python 3.14.2 2025-12-29 17:04:05 +01:00
CHANGELOG.md chore(release): 8.0.4 2025-12-31 09:51:46 +00:00
CODEOWNERS chore: set CODEOWNERS 2025-04-22 00:25:08 +00:00
conftest.py feat!: configurable bucket names, renamed MINIO_ to S3_ 2025-12-22 12:57:05 +01:00
docker-compose.yaml Merge branch 'renovate/python-3.x' into 'develop' 2025-12-24 09:48:12 +01:00
Dockerfile.integration fix(deps): update python docker tag to v3.14 2025-12-08 20:09:29 +00:00
LICENSE chore: add license 2025-04-15 00:20:36 +02:00
main.py chore: added integration test 2025-10-16 11:03:36 +02:00
poetry.lock fix(deps): update dependency minio to v7.2.20 2025-12-30 19:09:51 +00:00
pyproject.toml chore(release): 8.0.4 2025-12-31 09:51:46 +00:00
pytest.ini chore: add tests for worker class 2024-04-23 10:24:48 +00:00
README.md feat!: configurable bucket names, renamed MINIO_ to S3_ 2025-12-22 12:57:05 +01:00
renovate.json feat: commit dependency updates as fix 2025-09-16 11:20:27 +02:00

NLdoc Base Worker for Python

pipeline status coverage report Latest Release

A foundational worker implementation for Python projects in the NLdoc ecosystem. This library provides a robust base class for creating workers that handle AMQP message processing with built-in file storage capabilities.

Overview

The Base Worker provides a complete foundation for building distributed document processing workers. It handles:

  • AMQP Connection Management: Automatic connection setup, health monitoring, and graceful reconnection
  • Message Queue Processing: Structured job processing with configurable concurrency
  • File Storage Integration: Built-in MinIO integration for handling document assets
  • Worker Discovery: Automatic worker registration and health reporting
  • Error Handling: Comprehensive error types and graceful failure handling
  • Logging Integration: Built-in structured logging with ECS format
  • Utility Functions: Document processing utilities including bounding box operations and content extraction

Getting Started

Prerequisites

  • Python >= 3.11
  • Poetry >= 1.0.0
  • Access to an AMQP broker (RabbitMQ)
  • Optional: MinIO instance for file storage

Installation

Install the package via Poetry:

poetry add --source gitlab kimiworker

Or add to your pyproject.toml:

[tool.poetry.dependencies]
kimiworker = {version = "^4.14.8", source = "gitlab"}

[[tool.poetry.source]]
name = "gitlab"
url = "https://gitlab.com/api/v4/projects/48255673/packages/pypi/simple"
priority = "supplemental"

Basic Usage

Standard Initialization (v5.0.0+)

Use scope parameter for topic-based routing:

import kimiworker
import sys
import os
from typing import Optional
from kimiworker import KimiLogger, WorkerJob, PublishMethod
from kimiworker.types.remote_file_storage import RemoteFileStorageInterface

def job_handler(
    logger: KimiLogger,
    job: WorkerJob,
    job_id: str,
    local_file_path: Optional[str],
    remote_file_storage: RemoteFileStorageInterface,
    publish: PublishMethod
):
    """Handle incoming job processing."""
    logger.info(f"Processing job {job_id}")
    logger.info(f"Record ID: {job.get('recordId')}")
    logger.info(f"File Path: {local_file_path}")

    # Process your document here
    # Your document processing logic...

    # Publish the result
    publish("stringResult", "Processing completed", success=True, confidence=100)

if __name__ == '__main__':
    try:
        # Specify worker scope in format "inputtype-outputtype"
        # IMPORTANT:
        #   - Scope must use alphanumeric characters and hyphens only
        #   - Scope is automatically normalized to lowercase
        #   - Valid: "pdf-text", "image-json", "doc2-html5", "pdf-intermediate-json"
        #   - Invalid: "pdf.*", "pdf.text", "pdftext"
        worker = kimiworker.Worker(
            job_handler,
            scope="pdf-text"  # Worker scope (e.g., "pdf-text", "image-json") - normalized to lowercase
        )
        worker.start(number_of_concurrent_jobs=1)

    except KeyboardInterrupt:
        print('Got interruption signal. Exiting...\n')
        try:
            sys.exit(0)
        except SystemExit:
            os._exit(0)

Configuration

Environment Variables

Required environment variables for configuration:

AMQP Configuration

AMQP_HOST=localhost                              # AMQP broker host
AMQP_PORT=5672                                   # AMQP broker port
AMQP_USER=guest                                  # AMQP username
AMQP_PASS=guest                                  # AMQP password

# Topic-based routing (v5.0.0+)
NLDOC_TOPICS_EXCHANGE_NAME=nldoc.topics         # Topic exchange name (optional, defaults to "nldoc.topics")

S3 Configuration

S3_HOST=localhost        # S3/MinIO server host
S3_PORT=9000             # S3/MinIO server port
S3_ACCESS_KEY=minio      # S3/MinIO access key
S3_SECRET_KEY=minio123   # S3/MinIO secret key
S3_USE_SSL=true          # Use SSL for S3 connection (optional, defaults to true)
S3_REGION=eu-west-1      # S3 region (optional, defaults to "eu-west-1")

S3 Bucket Names (Optional)

S3_BUCKET_NAME_FILES=files              # Bucket for api uploads (defaults to "files")
S3_BUCKET_NAME_STATICASSETS=staticassets # Bucket for static assets from PDF documents (defaults to "staticassets")
S3_BUCKET_NAME_WORKER_DATA=worker-data  # Bucket for worker data (jobs and results) (defaults to "worker-data")
S3_BUCKET_NAME_PAGES=pages              # Bucket for page images (defaults to "pages")
S3_BUCKET_NAME_OUTPUT=output            # Bucket for output (spec, validation, json) (defaults to "output")

Optional Configuration

AMQP_HEARTBEAT_INTERVAL=60  # Heartbeat interval in seconds (optional, defaults to 60)
AMQP_NUM_PARTITIONS=20      # Number of queue partitions (optional, defaults to 20)
HOSTNAME=worker-instance-1  # Worker instance name (optional, defaults to pod/container hostname)

Job Handler

Your job handler receives the following parameters:

  • logger (KimiLogger): Structured logger with methods: info, warn, error
  • job (WorkerJob): The job information from the station
  • job_id (str): Auto-generated unique job identifier
  • local_file_path (Optional[str]): Path to downloaded file (if applicable)
  • remote_file_storage (RemoteFileStorageInterface): Connected MinIO storage interface
  • publish (PublishMethod): Callback for publishing results with parameters:
    • result (Any): The result data to send back
    • success (bool): Whether the job succeeded
    • confidence (int): Confidence level (0-100) of the result

Worker Features

Automatic Health Monitoring

Workers automatically report their availability status and handle graceful shutdowns.

File Storage Integration

Built-in MinIO integration provides seamless file access through the remote_file_storage interface.

Utility Functions

The library includes comprehensive utility functions:

  • Bounding Box Operations: Convert, manipulate, and analyze document regions
  • Content Extraction: Extract and merge content attributes from documents
  • Geometric Utilities: XY-cut recursive algorithms for document layout analysis

Error Handling

Comprehensive error handling with structured logging and graceful failure recovery.

KimiLogger - Structured Logging

KimiLogger provides structured logging in ECS (Elastic Common Schema) format with hierarchical context management:

from kimiworker import KimiLogger

# Initialize logger with base context
logger = KimiLogger(data={"userId": "123", "requestId": "abc"}, logger_name="my-worker")

# Standard logging methods
logger.debug("Debug message")
logger.info("Processing started")
logger.warning("Warning message")
logger.error("Error occurred")
logger.critical("Critical error")

# Create child loggers with inherited context
child_logger = logger.child({"step": "validation"})
child_logger.info("Validating input")  # Includes both parent and child context

# Log structured events
logger.event("userLogin", {"username": "john", "loginType": "oauth"})

Event Tracking with Duration Measurement

The timed_event context manager automatically tracks execution time and allows accumulating parameters during execution:

# Track execution time with accumulated parameters
with logger.timed_event("processDocument", {"documentId": "doc-123", "pages": 10}) as tracker:
    result = process_pages()
    tracker.add({"processedPages": result.count})

    if result.has_errors:
        tracker.add({"errors": result.errors})

# Automatically logs:
# - Event name: "processDocument"
# - All initial and accumulated parameters
# - Execution duration in seconds
# - Error information with stack trace (if an exception occurs)

Error Handling in Timed Events:

If an exception occurs within a timed_event context, the logger automatically captures:

  • Exception type
  • Error message
  • Full stack trace
  • Duration up to the point of failure
try:
    with logger.timed_event("riskyOperation", {"attempts": 3}) as tracker:
        tracker.add({"progress": "50%"})
        raise ValueError("Something went wrong")
except ValueError:
    # Event is logged with error details, stack trace, and partial progress
    pass

Legacy Track Method:

For simple callback-based timing:

# Track callback execution time
result = logger.track("dataProcessing", lambda: process_data(input), {"inputSize": 1000})

Available Utilities

Import utility functions for document processing:

from kimiworker.utils.bbox import (
    convert_bounding_box,
    bounding_box_to_dict,
    get_enclosing_bbox
)
from kimiworker.utils.worker_job import extract_best_attribute_value
from kimiworker.utils.xy_cut import xy_cut_recursive

Development

Local Setup

  1. Clone the repository:

    git clone https://gitlab.com/logius/nldoc/lib/python/baseworker.git
    cd baseworker
    
  2. Install Poetry (if not already installed):

    curl -sSL https://install.python-poetry.org | python3 -
    
  3. Install dependencies:

    poetry install
    
  4. Run tests:

    poetry run pytest
    

Available Scripts

  • poetry run pytest - Run the test suite
  • poetry run pytest --cov=kimiworker - Run tests with coverage
  • poetry build - Build the package
  • poetry publish - Publish the package
  • poetry install - Install dependencies
  • poetry update - Update dependencies

Testing

Run the test suite:

poetry run pytest

For coverage reports:

poetry run pytest --cov=kimiworker

To run tests in a specific file:

poetry run pytest kimiworker/test_worker.py

Integration Tests

Integration tests validate the worker with real RabbitMQ and MinIO services using a mock station.

docker-compose up --build
# Watch for test completion, then Ctrl+C
docker-compose down -v

See INTEGRATION_TESTS.md for details.

Contributing

We welcome contributions! Please ensure:

  1. All tests pass (poetry run pytest)
  2. Integration tests pass (see above)
  3. Code follows Python style guidelines
  4. Type hints are included where appropriate
  5. Documentation is updated for new features
  6. Dependencies are managed through Poetry (poetry add <package>)

License

This project is licensed under the European Union Public License 1.2 - see LICENSE for details.

Acknowledgements

  • Built on AMQP for reliable message queuing
  • Integrates with MinIO for object storage
  • Uses Pydantic for data validation