An open API service indexing awesome lists of open source software.

https://github.com/fenix-hub/u18n

A high-performance, scalable translation microservice built with Flask and ArgosTranslate, designed for ease of use and integration into any multilingual application.
https://github.com/fenix-hub/u18n

argos-translate cloud-native docker flask i18n internationalization microservice python

Last synced: 8 months ago
JSON representation

A high-performance, scalable translation microservice built with Flask and ArgosTranslate, designed for ease of use and integration into any multilingual application.

Awesome Lists containing this project

README

          

# u18n - Universal Translation Microservice

A high-performance, scalable translation microservice built with Flask and ArgosTranslate, designed for ease of use and integration into any multilingual application.

The microservice provides a robust translation API built on Flask and ArgosTranslate, with features like rate limiting, request throttling, and flexible configuration. The implementation follows best practices with proper error handling, middleware design, and comprehensive testing.

The service can handle various input and output formats, making it easy to integrate with different client applications. It's Docker-ready for easy deployment and includes health checks for monitoring.

## ๐ŸŒŸ Features

- **Multiple Translation Pairs**: Support for various language pairs (en-es, es-en, en-fr, fr-en, en-de, de-en)
- **Rate Limiting**: Protect your service with configurable rate limiting
- **Request Throttling**: Control concurrent request load
- **Multiple Input/Output Formats**: JSON and plain text support
- **Docker Ready**: Easy deployment with Docker and Docker Compose
- **Configurable**: YAML config files and environment variable overrides
- **Metrics**: Request tracking with detailed headers
- **Health Checks**: Built-in monitoring endpoint
- **Comprehensive API**: Well-documented RESTful endpoints

## ๐Ÿ“‹ API Endpoints

### Health Check
```
GET /health
```
Returns service status and installed language packages.

### Translation
```
POST /translate
```
Translates text from source language to target language.

**Input Formats:**
- JSON body:
```json
{
"text": "Hello world",
"source": "en",
"target": "es",
"outputFormat": "json"
}
```
- Form data with parameters: `text`, `source`, `target`, `outputFormat`

**Output Formats:**
- JSON:
```json
{
"translated": "Hola mundo",
"source": "en",
"target": "es",
"original": "Hello world"
}
```
- Plain text: `Hola mundo`

### Configuration
```
GET /config
```
Returns current service configuration.

```
PUT /config
```
Updates service configuration.

## ๐Ÿš€ Getting Started

### Prerequisites

- Docker and Docker Compose
- Python 3.9+ (for development without Docker)

### Running with Docker

1. Clone the repository:
```bash
git clone https://github.com/fenix-hub/u18n.git
cd u18n
```

2. Start the service using Docker Compose:
```bash
docker-compose up -d
```

3. The service will be available at http://localhost:5000

### Running Locally for Development

1. Create a virtual environment:
```bash
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
```

2. Install dependencies:
```bash
pip install -r requirements.txt
```

3. Run the service:
```bash
FLASK_APP=app/main.py python -m flask run
```

## โš™๏ธ Configuration

Configuration can be provided through:

1. Default values (built into the application)
2. YAML configuration file (`config/default_config.yml`)
3. Environment variables (highest priority)

### Environment Variables

| Variable | Description |
|----------|-------------|
| `CONFIG_PATH` | Path to YAML config file |
| `RATE_LIMIT_ENABLED` | Enable/disable rate limiting (true/false) |
| `RATE_LIMIT_RPM` | Requests per minute limit |
| `RATE_LIMIT_BURST` | Maximum burst size |
| `THROTTLING_ENABLED` | Enable/disable request throttling (true/false) |
| `THROTTLING_CONCURRENT` | Maximum concurrent requests |
| `MAX_CHARS_PER_REQUEST` | Character limit per translation request |
| `AVAILABLE_PACKAGES` | Comma-separated list of language pairs (e.g., "en-es,es-en") |
| `LOGGING_LEVEL` | Logging level (e.g., DEBUG, INFO, WARNING, ERROR) |
| `LOGGING_FORMAT` | Python logging format string |

### Sample Configuration

```yaml
logging:
level: "INFO"
format: "%(asctime)s - PID:%(process)d - %(name)s - %(levelname)s - %(message)s"

rate_limit:
requests_per_minute: 60
burst: 10
enabled: true

throttling:
concurrent_requests: 5
enabled: true

translation:
max_chars_per_request: 5000
available_packages:
- "en-es"
- "es-en"
- "en-fr"
- "fr-en"
- "en-de"
- "de-en"
- "it-en"
- "en-it"
fallback_response: "Translation service unavailable. Please try again later."

formats:
input:
- "json"
- "text"
output:
- "json"
- "text"
```

## ๐Ÿ“Š Response Headers

The service adds informative headers to responses:

### Rate Limiting Headers
- `X-RateLimit-Limit`: Maximum requests per minute
- `X-RateLimit-Remaining`: Remaining tokens
- `X-RateLimit-Reset`: Seconds until full reset
- `Retry-After`: Seconds to wait when rate limited

### Throttling Headers
- `X-Throttle-Limit`: Maximum concurrent requests
- `X-Throttle-Usage`: Current usage
- `X-Throttle-Remaining`: Available slots

### Translation Headers
- `X-Translation-Characters`: Character count of original text

## ๐Ÿงช Testing

Run tests with pytest:

```bash
pytest
```

Run with coverage report:

```bash
pytest --cov=app tests/
```

## ๐Ÿ”ง Architecture

The project follows a modular architecture with separate components for:

- **API Layer**: RESTful endpoints and request handling
- **Service Layer**: Business logic implementation
- **Configuration Management**: Dynamic config loading
- **Middleware**: Rate limiting and request throttling
- **Utilities**: Helper functions and decorators

### Project Structure

```
translation-service/
โ”œโ”€โ”€ Dockerfile # Docker image definition
โ”œโ”€โ”€ docker-compose.yml # Docker composition for easy deployment
โ”œโ”€โ”€ requirements.txt # Python dependencies
โ”œโ”€โ”€ README.md # Project documentation
โ”œโ”€โ”€ config/ # Configuration management
โ”‚ โ”œโ”€โ”€ __init__.py
โ”‚ โ”œโ”€โ”€ default_config.yml # Default configuration values
โ”‚ โ””โ”€โ”€ config_loader.py # Configuration loading logic
โ”œโ”€โ”€ app/ # Application code
โ”‚ โ”œโ”€โ”€ __init__.py # Logging configuration
โ”‚ โ”œโ”€โ”€ main.py # Application entry point
โ”‚ โ”œโ”€โ”€ api/ # API endpoints
โ”‚ โ”‚ โ”œโ”€โ”€ __init__.py
โ”‚ โ”‚ โ”œโ”€โ”€ routes.py # Route definitions
โ”‚ โ”‚ โ””โ”€โ”€ middleware.py # Request middleware
โ”‚ โ”œโ”€โ”€ services/ # Business logic services
โ”‚ โ”‚ โ”œโ”€โ”€ __init__.py
โ”‚ โ”‚ โ”œโ”€โ”€ translation_service.py # Translation logic
โ”‚ โ”‚ โ”œโ”€โ”€ rate_limiter.py # Rate limiting service
โ”‚ โ”‚ โ””โ”€โ”€ request_throttler.py # Request throttling service
โ”‚ โ””โ”€โ”€ utils/ # Utility functions
โ”‚ โ”œโ”€โ”€ __init__.py
โ”‚ โ””โ”€โ”€ helpers.py # Helper decorators and functions
โ””โ”€โ”€ tests/ # Test suite
โ”œโ”€โ”€ __init__.py
โ”œโ”€โ”€ test_api.py # API tests
โ”œโ”€โ”€ test_translation.py # Translation service tests
โ””โ”€โ”€ test_config.py # Configuration tests
```

## ๐Ÿ“– About ArgosTranslate

This service uses [ArgosTranslate](https://github.com/argosopentech/argos-translate), an open-source neural machine translation library that allows for offline translation. It supports multiple language pairs and uses lightweight models suitable for containerized deployments.

## ๐Ÿ“ Performance Considerations

- **Model Download**: Language models are downloaded on first use, which may cause initial delays
- **Memory Usage**: Consider container memory limits based on the number of language pairs loaded
- **Caching**: API responses are not cached; consider implementing a caching layer for frequent translations
- **Scaling**: For high-volume scenarios, deploy multiple instances behind a load balancer

## ๐Ÿ›ก๏ธ Security Notes

- The service does not implement authentication; consider adding API keys or OAuth2
- Request rates are tracked by IP address; implement user-based tracking for multi-user scenarios
- Add HTTPS for production deployments

## ๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## ๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.