Metadata-Version: 2.4
Name: locale-plus
Version: 0.2.0
Summary: Simplified internationalization (i18n) in Python. Locale format conversion between Windows and Unix systems, convenient loading of .mo translation files
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: bidict>=0.23.1
Requires-Dist: pathlike-typing>=1.0.0
Dynamic: license-file

<a id="doc_en"></a>
# locale-plus 🌍
#### [Документация на русском](#doc_ru)

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

Simplified internationalization (i18n) in Python. Locale format conversion between Windows and Unix systems, convenient loading of `.mo` translation files.

## Features

- 🔄 **Locale conversion** between Windows (e.g., `Russian_Russia`) and Unix formats (`ru_RU`)
- 🌐 **Determine the current system locale** with automatic conversion
- 📖 **Load GNU gettext translations** from `.mo` files
- 💾 **Cache translations** for optimal performance
- 🔧 **Support for singular and plural forms** (plural forms)

## Installation

```bash
pip install locale-plus
```

Or for development:

```bash
git clone https://github.com/yourusername/locale-plus.git
cd locale-plus
pip install -e .
```

## Requirements
- Python 3.8 or higher
- `bidict >= 0.23.1`
- `pathlike-typing >= 1.0.0`

## Quick Start
### Locale Conversion
```python
from locale_plus import LocaleConverter

# Get the current system locale
current = LocaleConverter.current_language
print(current)  # 'ru_RU' or 'en_US' etc.

# Convert Windows -> Unix
unix_locale = LocaleConverter.convert_windows_to_unix('Russian_Russia')
print(unix_locale)  # 'ru_RU'

# Convert Unix -> Windows
windows_locale = LocaleConverter.convert_unix_to_windows('ru_RU')
print(windows_locale)  # 'Russian_Russia'
```

### Using Translations
Directory structure for translation files:
```text
locales/
├── ru_RU/
│   └── LC_MESSAGES/
│       └── messages.mo
├── en_US/
│   └── LC_MESSAGES/
│       └── messages.mo
└── de_DE/
    └── LC_MESSAGES/
        └── messages.mo
```

```python
from locale_plus import Internationalizator

# Create an object for the Russian locale
i18n = Internationalizator(
    locale_dir='locales',
    language_code='ru_RU',
    domain='messages'
)

# Simple Translation
print(i18n.gettext('Hello World!'))  # 'Hello World!'

# Translation with Plural Forms
for i in range(5):
    print(i18n.ngettext(f'{i} file', f'{i} files', i))
```

### Working with Locale Dictionaries
```python
from locale_plus import LocaleConverter

# Get all Windows -> Unix mappings
win_to_unix = LocaleConverter.windows_unix_locales
print(win_to_unix['Russian_Russia'])  # 'ru_RU'

# Get all Unix -> Windows mappings
unix_to_win = LocaleConverter.unix_windows_locales
print(unix_to_win['ru_RU'])  # 'Russian_Russia'
```

## API Reference
### LocaleConverter (static class)

| Property/Method                  | Description                                      |
|---------------------------------|--------------------------------------------------|
| windows_unix_locales            | Dictionary mapping Windows → Unix formats       |
| unix_windows_locales            | Dictionary mapping Unix → Windows formats       |
| convert_windows_to_unix(locale) | Converts a Windows locale to Unix format        |
| convert_unix_to_windows(locale) | Converts a Unix locale to Windows format        |
| current_language                | Returns the current system locale in Unix format|

### Internationalizator
```python
Internationalizator(locale_dir, language_code, domain)
```

| Parameter      | Type     | Description                               |
|----------------|----------|-------------------------------------------|
| locale_dir     | PathLike | Path to the directory with locale files   |
| language_code  | str      | Language code (e.g., 'ru_RU')             |
| domain         | str      | Translation domain (the .mo file name)    |

#### Methods:
- `gettext(message)` - translates a string
- `ngettext(singular, plural, n)` - translates with plural forms support
- `pgettext(context)` - translation with context support
- `npgettext(context)` - translation with context and plural form support

## Supported Locales
The module supports conversion for 35 popular locales:

| Language                    | Windows                | Unix  |
|-----------------------------|------------------------|-------|
| Russian                     | Russian_Russia         | ru_RU |
| English (USA)               | English_United States  | en_US |
| English (UK)                | English_United Kingdom | en_GB |
| German                      | German_Germany         | de_DE |
| French                      | French_France          | fr_FR |
| Spanish                     | Spanish_Spain          | es_ES |
| Chinese                     | Chinese_China          | zh_CN |
| Japanese                    | Japanese_Japan         | ja_JP |
| ...and others               | ...                    | ...   |

## Development
### Installation for Development
```bash
git clone https://github.com/yourusername/locale_plus.git
cd locale_plus
pip install -e ".[dev]"
```

### Building the Package
```bash
python -m build
```

## License
MIT License. See the [LICENSE](https://github.com/MagIlyasDOMA/locale_plus/blob/main/LICENSE) file for details.

## Author
Mag Ilyas DOMA (MagIlyasDOMA) - [@MagIlyasDOMA](https://github.com/MagIlyasDOMA/)

## Acknowledgements
- `bidict` library for efficient bidirectional dictionaries
- GNU gettext for the translation file standard

#### ⭐ Please star if the project was useful!

---

<a id="doc_ru"></a>
# locale-plus 🌍
#### [Documentation in English](#doc_en)

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

Упрощённая работа с интернационализацией (i18n) в Python. Конвертация форматов локалей между Windows и Unix системами, удобная загрузка `.mo` файлов переводов.

## Возможности

- 🔄 **Конвертация локалей** между Windows (например, `Russian_Russia`) и Unix форматами (`ru_RU`)
- 🌐 **Определение текущей локали** системы с автоматической конвертацией
- 📖 **Загрузка GNU gettext переводов** из `.mo` файлов
- 💾 **Кэширование переводов** для оптимальной производительности
- 🔧 **Поддержка единственного и множественного числа** (plural forms)

## Установка

```bash
pip install locale-plus
```

Или для разработки:

```bash
git clone https://github.com/yourusername/locale-plus.git
cd locale-plus
pip install -e .
```

## Требования
- Python 3.8 или выше
- `bidict >= 0.23.1`
- `pathlike-typing >= 1.0.0`

## Быстрый старт
### Конвертация локалей
```python
from locale_plus import LocaleConverter

# Определение текущей локали системы
current = LocaleConverter.current_language
print(current)  # 'ru_RU' или 'en_US' и т.д.

# Конвертация Windows -> Unix
unix_locale = LocaleConverter.convert_windows_to_unix('Russian_Russia')
print(unix_locale)  # 'ru_RU'

# Конвертация Unix -> Windows
windows_locale = LocaleConverter.convert_unix_to_windows('ru_RU')
print(windows_locale)  # 'Russian_Russia'
```

### Использование переводов
Структура директорий для файлов переводов:
```text
locales/
├── ru_RU/
│   └── LC_MESSAGES/
│       └── messages.mo
├── en_US/
│   └── LC_MESSAGES/
│       └── messages.mo
└── de_DE/
    └── LC_MESSAGES/
        └── messages.mo
```

```python
from locale_plus import Internationalizator

# Создаём объект для русской локали
i18n = Internationalizator(
    locale_dir='locales',
    language_code='ru_RU',
    domain='messages'
)

# Простой перевод
print(i18n.gettext('Hello World!'))  # 'Привет Мир!'

# Перевод с учётом множественного числа
for i in range(5):
    print(i18n.ngettext(f'{i} file', f'{i} files', i))
```

### Работа со словарями локалей
```python
from locale_plus import LocaleConverter

# Получить все соответствия Windows -> Unix
win_to_unix = LocaleConverter.windows_unix_locales
print(win_to_unix['Russian_Russia'])  # 'ru_RU'

# Получить все соответствия Unix -> Windows
unix_to_win = LocaleConverter.unix_windows_locales
print(unix_to_win['ru_RU'])  # 'Russian_Russia'
```

## API Справка
### LocaleConverter (статический класс)

| Свойство/Метод                  | Описание                                           |
|---------------------------------|----------------------------------------------------|
| windows_unix_locales            | Словарь соответствия Windows → Unix форматов       |
| unix_windows_locales            | Словарь соответствия Unix → Windows форматов       |
| convert_windows_to_unix(locale) | Конвертирует Windows локаль в Unix формат          |
| convert_unix_to_windows(locale) | Конвертирует Unix локаль в Windows формат          |
| current_language                | Возвращает текущую системную локаль в Unix формате |

### Internationalizator
```python
Internationalizator(locale_dir, language_code, domain)
```

| Параметр      | Тип      | Описание                            |
|---------------|----------|-------------------------------------|
| locale_dir    | PathLike | Путь к директории с файлами локалей |
| language_code | str      | Код языка (например, 'ru_RU')       |
| domain        | str      | Имя домена перевода (имя .mo файла) |

#### Методы:
- `gettext(message)` - перевод строки
- `ngettext(singular, plural, n)` - перевод с поддержкой plural forms
- `pgettext(context)` - перевод с поддержкой контекста
- `npgettext(context)` - перевод с поддержкой контекста и plural forms

## Поддерживаемые локали
Модуль поддерживает конвертацию для 35 популярных локалей:

| Язык                        | Windows                | Unix  |
|-----------------------------|------------------------|-------|
| Русский                     | Russian_Russia         | ru_RU |
| Английский (США)            | English_United States  | en_US |
| Английский (Великобритания) | English_United Kingdom | en_GB |
| Немецкий	                   | German_Germany         | de_DE |
| Французский	                | French_France          | fr_FR |
| Испанский	                  | Spanish_Spain          | es_ES |
| Китайский                   | 	Chinese_China         | zh_CN |
| Японский                    | 	Japanese_Japan        | ja_JP |
| ...и другие                 | 	...                   | 	...  |

## Разработка
### Установка для разработки
```bash
git clone https://github.com/yourusername/locale_plus.git
cd locale_plus
pip install -e ".[dev]"
```

### Сборка пакета
```bash
python -m build
```

## Лицензия
MIT License. См. файл [LICENSE](https://github.com/MagIlyasDOMA/locale_plus/blob/main/LICENSE) для деталей.

## Автор
Маг Ильяс DOMA (MagIlyasDOMA) - [@MagIlyasDOMA](https://github.com/MagIlyasDOMA/)

## Благодарности
- Библиотека `bidict` для эффективных двунаправленных словарей
- GNU gettext для стандарта файлов переводов

#### ⭐ Поставьте звезду, если проект оказался полезным!
