- Python 100%
| .vscode | ||
| integration | ||
| kimiworker | ||
| .editorconfig | ||
| .gitignore | ||
| .gitlab-ci.yml | ||
| .python-version | ||
| CHANGELOG.md | ||
| CODEOWNERS | ||
| conftest.py | ||
| docker-compose.yaml | ||
| Dockerfile.integration | ||
| LICENSE | ||
| main.py | ||
| poetry.lock | ||
| pyproject.toml | ||
| pytest.ini | ||
| README.md | ||
| renovate.json | ||
NLdoc Base Worker for Python
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,errorjob(WorkerJob): The job information from the stationjob_id(str): Auto-generated unique job identifierlocal_file_path(Optional[str]): Path to downloaded file (if applicable)remote_file_storage(RemoteFileStorageInterface): Connected MinIO storage interfacepublish(PublishMethod): Callback for publishing results with parameters:result(Any): The result data to send backsuccess(bool): Whether the job succeededconfidence(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
-
Clone the repository:
git clone https://gitlab.com/logius/nldoc/lib/python/baseworker.git cd baseworker -
Install Poetry (if not already installed):
curl -sSL https://install.python-poetry.org | python3 - -
Install dependencies:
poetry install -
Run tests:
poetry run pytest
Available Scripts
poetry run pytest- Run the test suitepoetry run pytest --cov=kimiworker- Run tests with coveragepoetry build- Build the packagepoetry publish- Publish the packagepoetry install- Install dependenciespoetry 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:
- All tests pass (
poetry run pytest) - Integration tests pass (see above)
- Code follows Python style guidelines
- Type hints are included where appropriate
- Documentation is updated for new features
- 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.