### Install RUAccent Library
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Install the RUAccent library using pip. You can also install directly from GitHub.
```bash
# Установка через pip
pip install ruaccent
# Альтернативная установка напрямую из GitHub
pip install git+https://github.com/Den4ikAI/ruaccent.git
```
--------------------------------
### Install RUAccent
Source: https://github.com/den4ikai/ruaccent/blob/main/README.md
Installation commands for the library using pip or directly from the repository.
```bash
pip install ruaccent
```
```bash
pip install git+https://github.com/Den4ikAI/ruaccent.git
```
--------------------------------
### Basic Usage Example
Source: https://github.com/den4ikai/ruaccent/blob/main/README.md
Initialization and processing of text to add stress marks.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True, tiny_mode=False)
text = 'на двери висит замок.'
print(accentizer.process_all(text))
```
--------------------------------
### Custom Dictionary Format
Source: https://github.com/den4ikai/ruaccent/blob/main/README.md
Example of the dictionary format for providing custom stress placement.
```python
{'слово': 'сл+ово с удар+ением'}
```
--------------------------------
### Initialize RUAccent and Process Text
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Initialize the RUAccent class and load models. Then, process a given text to get the result with accents.
```python
from ruaccent import RUAccent
# Создание экземпляра класса
accentizer = RUAccent()
# Загрузка моделей и словарей
accentizer.load(
omograph_model_size='turbo3.1', # Модель для разрешения омографов
use_dictionary=True, # Использовать полный словарь ударений
tiny_mode=False # Полный режим работы
)
# Обработка текста
text = 'на двери висит замок.'
result = accentizer.process_all(text)
print(result)
# Вывод: на двер+и вис+ит зам+ок.
```
--------------------------------
### Process Text
Source: https://github.com/den4ikai/ruaccent/blob/main/README.md
Example of how to use the library to process text and add stress marks.
```APIDOC
## Method: process_all
### Description
Processes the input string and returns the text with stress marks applied.
### Request Example
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True, tiny_mode=False)
text = 'на двери висит замок.'
print(accentizer.process_all(text))
```
```
--------------------------------
### Accelerate processing with GPU (CUDA)
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Speed up text processing on a GPU by installing `onnxruntime-gpu` and setting `device='CUDA'` during model loading. This is beneficial for handling large volumes of text.
```python
from ruaccent import RUAccent
# Предварительно установите: pip install onnxruntime-gpu
accentizer = RUAccent()
accentizer.load(
omograph_model_size='turbo3.1',
use_dictionary=True,
device='CUDA' # Использовать GPU
)
# Обработка больших объёмов текста на GPU
long_text = '''
Русский язык — один из восточнославянских языков,
национальный язык русского народа.
Является одним из наиболее распространённых языков мира.
''' * 100 # Большой текст для демонстрации
result = accentizer.process_all(long_text)
print(f'Обработано {len(long_text)} символов')
```
--------------------------------
### Restore the letter 'ё'
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Use the `process_yo` method to restore the letter 'ё' in Russian text. This is useful for texts where 'е' might be ambiguous. The method handles single texts and lists of examples.
```python
text = 'Все ежики пришли домой'
result = accentizer.process_yo(text)
print(result)
```
```python
examples = [
'елка стоит в углу',
'мед очень вкусный',
'зеленый самолет'
]
for example in examples:
print(f'{example} -> {accentizer.process_yo(example)}')
```
--------------------------------
### Configure RUAccent Load Method
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Demonstrates the full configuration of the `load` method, including custom dictionaries, homographs, device selection, and working directory.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
# Полная конфигурация метода load()
accentizer.load(
omograph_model_size='turbo3.1', # Размер модели: 'tiny', 'tiny2', 'tiny2.1',
# 'turbo', 'turbo2', 'turbo3', 'turbo3.1', 'big_poetry'
use_dictionary=True, # True - полный словарь (больше ОЗУ),
# False - только нейросеть
custom_dict={
'кошка': 'к+ошка',
'собака': 'соб+ака'
},
custom_homographs={
'коса': ['к+оса', 'кос+а']
},
device='CPU', # Устройство: 'CPU' или 'CUDA'
workdir='/path/to/models', # Путь для сохранения моделей (опционально)
tiny_mode=False # True - облегчённый режим (меньше моделей)
)
```
```python
# Пример с минимальными ресурсами (для слабых устройств)
accentizer_light = RUAccent()
accentizer_light.load(
omograph_model_size='tiny',
use_dictionary=False,
tiny_mode=True,
device='CPU'
)
```
```python
# Пример с GPU ускорением (требуется onnxruntime-gpu)
accentizer_gpu = RUAccent()
accentizer_gpu.load(
omograph_model_size='turbo3.1',
use_dictionary=True,
device='CUDA'
)
```
--------------------------------
### Method load()
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Initializes the RUAccent instance by loading neural network models and dictionaries. Supports configuration for model size, hardware device, and custom dictionaries.
```APIDOC
## load(omograph_model_size, use_dictionary, custom_dict, custom_homographs, device, workdir, tiny_mode)
### Description
Loads the necessary models and dictionaries for stress marking. Automatically downloads files from HuggingFace Hub on the first call.
### Parameters
- **omograph_model_size** (string) - Optional - Model size: 'tiny', 'tiny2', 'tiny2.1', 'turbo', 'turbo2', 'turbo3', 'turbo3.1', 'big_poetry'.
- **use_dictionary** (boolean) - Optional - Whether to use the full dictionary (requires more RAM).
- **custom_dict** (dict) - Optional - User-defined dictionary for specific word stresses.
- **custom_homographs** (dict) - Optional - User-defined homograph mappings.
- **device** (string) - Optional - Hardware device: 'CPU' or 'CUDA'.
- **workdir** (string) - Optional - Directory path for storing models.
- **tiny_mode** (boolean) - Optional - Enables lightweight mode with fewer models.
```
--------------------------------
### RUAccent Initialization and Configuration
Source: https://github.com/den4ikai/ruaccent/blob/main/README.md
Details on how to initialize the RUAccent object and configure the model loading parameters.
```APIDOC
## Method: load
### Description
Initializes the accentuation model and loads necessary resources into memory.
### Parameters
- **omograph_model_size** (string) - Optional - Model size options: 'tiny', 'tiny2', 'tiny2.1', 'turbo2', 'turbo3', 'turbo3.1', 'turbo', 'big_poetry'. Default: 'turbo2'.
- **use_dictionary** (boolean) - Optional - If True, loads the full dictionary (requires more RAM). If False, stress is placed by the neural network only.
- **custom_dict** (object) - Optional - Dictionary for custom stress overrides. Format: {'word': 'w+ord with str+ess'}.
- **device** (string) - Optional - Processing device: 'CPU' or 'CUDA'.
- **workdir** (string) - Optional - Path to directory for downloading models.
- **tiny_mode** (boolean) - Optional - If True, disables rule-based pipeline and dictionary loading.
```
--------------------------------
### Configure RUAccent Parameters
Source: https://github.com/den4ikai/ruaccent/blob/main/README.md
Function signature for loading models and configuring dictionary usage, device, and working directory.
```python
load(omograph_model_size='turbo2', use_dictionary=True, custom_dict={}, device="CPU", workdir=None)
```
--------------------------------
### Select an omograph model for stress resolution
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Choose from various omograph models ('tiny', 'turbo3.1', 'big_poetry') to balance processing speed and accuracy. The 'turbo3.1' model is recommended for general use, while 'big_poetry' offers maximum quality for poetry.
```python
from ruaccent import RUAccent
# Доступные модели омографов:
# - 'tiny' - минимальный размер, быстрая работа, базовое качество
# - 'tiny2' - улучшенная tiny модель
# - 'tiny2.1' - последняя версия tiny
# - 'turbo' - баланс скорости и качества
# - 'turbo2' - улучшенная turbo модель
# - 'turbo3' - ещё более точная turbo
# - 'turbo3.1' - рекомендуемая модель (баланс качества и скорости)
# - 'big_poetry' - максимальное качество для поэзии
# Пример: сравнение моделей
test_text = 'Старый замок на холме был разрушен'
models = ['tiny', 'turbo3.1', 'big_poetry']
for model_name in models:
accentizer = RUAccent()
accentizer.load(omograph_model_size=model_name, use_dictionary=True)
result = accentizer.process_all(test_text)
print(f'[{model_name}]: {result}')
# Рекомендации по выбору модели:
# - Минимум ОЗУ (512 МБ): tiny + tiny_mode=True
# - Обычное использование: turbo3.1
# - Поэзия и высокое качество: big_poetry
```
--------------------------------
### Method process_all()
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Performs full text processing, including yo-restoration, homograph resolution, and stress marking.
```APIDOC
## process_all(text, skip_regex)
### Description
Processes the input text to add stress marks to words and resolve homographs based on context.
### Parameters
- **text** (string) - Required - The input text to process.
- **skip_regex** (string) - Optional - A regular expression to identify parts of the text that should be ignored during processing.
### Response
- **result** (string) - The processed text with stress marks (e.g., 'зам+ок').
```
--------------------------------
### Process Text File Line by Line with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Read a text file, process each line individually for accentuation, and write the results to an output file. Ensure UTF-8 encoding for both input and output files.
```python
# Обработка файла построчно
def process_file(input_path, output_path):
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
with open(input_path, 'r', encoding='utf-8') as f_in:
with open(output_path, 'w', encoding='utf-8') as f_out:
for line in f_in:
processed = accentizer.process_all(line.strip())
f_out.write(processed + '\n')
# Использование: process_file('input.txt', 'output.txt')
```
--------------------------------
### Enable tiny_mode for resource-constrained environments
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Utilize `tiny_mode=True` for reduced memory consumption and faster processing on devices with limited resources. This mode disables certain models and the rule-based pipeline. It requires approximately 512 MB of RAM when `use_dictionary=False`.
```python
from ruaccent import RUAccent
# Облегчённый режим для слабых устройств
accentizer = RUAccent()
accentizer.load(
omograph_model_size='tiny',
use_dictionary=False, # Не загружать полный словарь
tiny_mode=True # Отключить дополнительные модели
)
# Работает быстрее, требует меньше памяти
text = 'Привет, как твои дела сегодня?'
result = accentizer.process_all(text)
print(result)
# Вывод: Прив+ет, как тво+и дел+а сег+одня?
# Сравнение потребления памяти:
# - tiny_mode=True, use_dictionary=False: ~512 МБ ОЗУ
# - tiny_mode=False, use_dictionary=True: ~1-2 ГБ ОЗУ
```
--------------------------------
### Batch Process Multiple Texts with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Process a list of texts efficiently by initializing the model once. This is suitable for handling multiple independent text inputs in a loop.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
# Список текстов для обработки
texts = [
'Мама мыла раму',
'На двери висит замок',
'Старый замок на холме',
'Я люблю читать книги',
'Сегодня хорошая погода'
]
# Пакетная обработка
results = []
for text in texts:
result = accentizer.process_all(text)
results.append(result)
print(f'"{""}{text}"" -> "{""}{result}""')
```
--------------------------------
### Use a custom dictionary for accentuation
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Enhance accentuation accuracy by providing a custom dictionary with specific stress patterns for words, names, or terms. The dictionary format is {'word': 'word+with+stress'}.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
# Словарь с пользовательскими ударениями
# Формат: {'слово': 'сл+ово с удар+ением'}
custom_dictionary = {
'анна': '+анна',
'питон': 'пит+он',
'москва': 'москв+а',
'tensorflow': 't+ensorflow',
'нейросеть': 'нейрос+еть'
}
accentizer.load(
omograph_model_size='turbo3.1',
use_dictionary=True,
custom_dict=custom_dictionary
)
# Тестирование пользовательских ударений
texts = [
'Привет, Анна!',
'Изучаю питон',
'Живу в Москва'
]
for text in texts:
print(f'{text} -> {accentizer.process_all(text)}')
```
--------------------------------
### Integrate RUAccent for TTS Preprocessing
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Prepare text for Text-to-Speech (TTS) systems by restoring 'ё' and setting correct accents. This class handles both plain text and SSML-formatted text, preserving SSML tags during processing.
```python
from ruaccent import RUAccent
class TTSPreprocessor:
def __init__(self):
self.accentizer = RUAccent()
self.accentizer.load(
omograph_model_size='turbo3.1',
use_dictionary=True
)
def preprocess(self, text: str) -> str:
"""Подготовка текста для TTS системы"""
# Восстановление ё и расстановка ударений
processed = self.accentizer.process_all(text)
return processed
def preprocess_ssml(self, text: str) -> str:
"""Обработка с сохранением SSML тегов"""
# Пропускаем SSML теги при обработке
processed = self.accentizer.process_all(
text,
skip_regex=r'<[^>]+>'
)
return processed
# Использование
preprocessor = TTSPreprocessor()
# Обычный текст
text = 'Привет! Как твои дела сегодня?'
tts_input = preprocessor.preprocess(text)
print(f'TTS input: {tts_input}')
# Вывод: TTS input: Прив+ет! Как тво+и дел+а сег+одня?
# Текст с SSML разметкой
ssml_text = 'Привет Как дела?'
tts_ssml_input = preprocessor.preprocess_ssml(ssml_text)
print(f'SSML input: {tts_ssml_input}')
# Вывод: SSML input: Прив+ет Как дел+а?
```
--------------------------------
### Process Text with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Utilize the `process_all` method for comprehensive text processing, including accentuation, homograph resolution, and 'yo' restoration. Supports regex-based skipping and multi-line text.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
# Базовая обработка текста
text1 = 'Привет, как дела?'
result1 = accentizer.process_all(text1)
print(result1)
# Вывод: Прив+ет, как дел+а?
```
```python
# Обработка омографов (контекстно-зависимое ударение)
text2 = 'на двери висит замок' # замо́к (дверной)
text3 = 'старинный замок на холме' # за́мок (крепость)
print(accentizer.process_all(text2))
# Вывод: на двер+и вис+ит зам+ок
print(accentizer.process_all(text3))
# Вывод: стар+инный з+амок на холм+е
```
```python
# Обработка с regex-исключениями (skip_regex)
# Пропустить части текста, соответствующие регулярному выражению
text_with_tags = 'Привет как дела '
result = accentizer.process_all(text_with_tags, skip_regex=r'<[^>]+>')
print(result)
# Вывод: Прив+ет как дел+а
```
```python
# Обработка многострочного текста
long_text = '''
Мама мыла раму.
На двери висит замок.
Старый замок разрушен.
'''
result = accentizer.process_all(long_text)
print(result)
```
--------------------------------
### Method process_yo()
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Restores the letter 'ё' in text without applying stress marks.
```APIDOC
## process_yo(text)
### Description
Replaces 'е' with 'ё' where appropriate based on the loaded model.
### Parameters
- **text** (string) - Required - The input text to process.
### Response
- **result** (string) - The text with restored 'ё' characters.
```
--------------------------------
### Skip URLs with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Exclude URLs from accentuation by using a regex pattern that matches common URL formats. This preserves the integrity of web addresses in the processed output.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
# Пропуск URL
text_with_url = 'Посмотри на сайте https://example.com'
result = accentizer.process_all(text_with_url, skip_regex=r'https?://\S+')
print(result)
# Вывод: Посмотр+и на с+айте https://example.com
```
--------------------------------
### Skip HTML/XML Tags with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Process text while ignoring HTML or XML tags by providing a regular expression to the skip_regex parameter. This ensures tags are not altered during accentuation.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
# Пропуск HTML/XML тегов
html_text = 'Привет
мир'
result = accentizer.process_all(html_text, skip_regex=r'<[^>]+>')
print(result)
# Вывод: Прив+ет
м+ир
```
--------------------------------
### Use custom homographs for context-dependent stress
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Handle words with multiple stress possibilities based on context by defining custom homographs. The format is {'word': ['variant1+with+stress', 'variant2+with+stress']}.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
# Пользовательские омографы
# Формат: {'слово': ['вари+ант1', 'вариа+нт2']}
custom_homographs = {
'атлас': ['+атлас', 'атл+ас'], # атлас (карта) vs атлас (ткань)
'ирис': ['+ирис', 'ир+ис'], # ирис (цветок) vs ирис (конфета)
'хлопок': ['хл+опок', 'хлоп+ок'] # хлопок (звук) vs хлопок (растение)
}
accentizer.load(
omograph_model_size='turbo3.1',
use_dictionary=True,
custom_homographs=custom_homographs
)
# Контекстное разрешение омографов
texts = [
'Посмотри на географический атлас',
'Платье из атласа очень красивое',
'В саду расцвёл ирис',
'Дети любят ирис'
]
for text in texts:
print(f'{text} -> {accentizer.process_all(text)}')
```
--------------------------------
### Restore 'yo' Letter with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Use the `process_yo` method for specialized replacement of 'e' with 'yo' where appropriate, without accent placement.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
```
--------------------------------
### Skip Email Addresses with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Prevent accentuation of email addresses by specifying a regex pattern that matches email formats. This ensures email addresses remain unchanged in the processed text.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
# Пропуск email адресов
text_with_email = 'Напиши мне на example@mail.ru сегодня'
result = accentizer.process_all(text_with_email, skip_regex=r'\S+@\S+\.\S+')
print(result)
# Вывод: Напиш+и мн+е на example@mail.ru сег+одня
```
--------------------------------
### Skip Special Markers with RUAccent
Source: https://context7.com/den4ikai/ruaccent/llms.txt
Exclude specific markers or patterns within the text from accentuation by using a custom regular expression in skip_regex. This is useful for placeholders or custom notations.
```python
from ruaccent import RUAccent
accentizer = RUAccent()
accentizer.load(omograph_model_size='turbo3.1', use_dictionary=True)
# Пропуск специальных маркеров
text_with_markers = 'Привет [NAME] как твои дела [PAUSE]'
result = accentizer.process_all(text_with_markers, skip_regex=r'\[[A-Z_]+\]')
print(result)
# Вывод: Прив+ет [NAME] как тво+и дел+а [PAUSE]
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.