Нутрощі Weblate¶
Примітка
У цьому розділі наведено базовий огляд нутрощів Weblate.
Структура більшої частини коду Weblate походить від Django і засновано на структурі коду Django.
Структура каталогів¶
Короткий огляд структури каталогів основного сховища Weblate:
docsПочатковий код цієї документації, який можна зібрати за допомогою Sphinx.
dev-dockerКод Docker для запуску сервера розробки, див. Запуск Weblate локально у Docker.
weblateВихідний код Weblate як програми Django, див. Нутрощі Weblate.
weblate/staticКлієнтські файли (CSS, Javascript і зображення), див. Оболонка Weblate.
Модулі¶
Weblate складається з декількох програм Django (деякі є необов’язковими, див. Додаткові модулі Weblate):
accounts
Обліковий запис користувача, профілі та сповіщення.
addons
Додатки для коригування поведінки Weblate, див. Додатки.
api
Програмний інтерфейс на основі Django REST framework.
auth
Розпізнавання і права доступу.
billing
Додатковий модуль Оплата.
checks
Модуль Перевірки якості для рядків перекладів.
fonts
Модуль перевірок обробки шрифтів.
formats
Шар абстракції форматів файлів на основі translate-toolkit.
gitexport
Додатковий модуль Засіб експортування Git.
lang
Модуль визначення мов і моделей форм множини.
legal
Додатковий модуль Юридичний модуль.
machinery
Інтеграція служб комп’ютерного перекладу.
memory
Вбудована пам’ять перекладів, див. Пам’ять перекладів.
screenshots
Керування знімками вікон та модуль оптичного розпізнавання тексту.
trans
Головний модуль для обробки перекладів.
utils
Різноманітні допоміжні інструменти.
vcs
Абстракція системи керування версіями.
wladmin
Налаштовування адміністративного інтерфейсу Django.
Translation sources¶
A unit has a canonical file source and may have a translation from another
language as its effective source. Keep Unit.source and Unit.source_unit
canonical: repository synchronization and file formats depend on this. Use
effective_source and its language and plural accessors for content shown to
translators. Do not replace source on a copied unit to simulate an effective
source; other fields and related objects still describe the canonical source.
Use Unit.source_snapshot when an operation needs to preserve the source text,
language, plural rules, and terminology metadata together. Its identity defines source changes for
dependency reconciliation, editor conflict detection, and AI diagnostics. For
historical rendering and reports, read the snapshot recorded on the change,
rather than reconstructing it from the current unit.
A missing configured parent remains a custom source: its text is empty, its
language is retained, and its child is blocked. effective_source_unit is
then None. Only removing the workflow or selecting the canonical language
restores the canonical source.
Text-only accessors do not load language or plural metadata. For batch consumers
that need the complete effective source, use
UnitQuerySet.prefetch_translation_parent() alongside their existing unit
prefetches. prefetch_source() already includes this. Ordinary searches keep
the canonical query path and ordinary units retain their existing content hashes.
Source-dependent writes enter source_operation() before locking unit rows.
The outer operation takes a shared project gate and reads its workflow mapping
in one database round trip, including for projects without custom workflows.
Workflow changes take source_project_gate(..., exclusive=True) before
validation or persistence. Configuration changes affecting several projects
acquire their gates in ascending project ID order. Never upgrade a shared gate
to an exclusive one inside an operation.
The database gate function locks first and reads workflows in a separate statement, so a waiter sees configuration committed while it waited. Write paths use this transaction-scoped view rather than cached model settings. Nested operations reuse it; rolled-back savepoints discard their dependency work. Queued dependencies are reconciled before commit and external memory updates are scheduled after commit. Source-change history is written in bulk, preserving individual records while batching their notification dispatch.
Acquire any required repository locks before project gates, then component and unit row locks. Reconciliation itself only changes database state and does not acquire repository locks. Apply this boundary to bulk imports, automatic translation, file-save failures, deletion, and restoration as well as editor writes. Language and plural-rule changes require exclusive gates before their updates. Historical migrations use historical models without these runtime helpers.
Machinery source selection happens before mapping language codes to a provider.
Use get_unit_source_language() for translation and uses_custom_source()
for workflow-specific glossary handling. Provider codes can merge distinct
language variants, so code equality cannot determine whether a workflow source
was selected. Explicit component or secondary source selection takes precedence
over the workflow source.
Внутрішні функції фонових завдань¶
Підказка
У цьому розділі описано внутрішню роботу завдань Celery. Фонові завдання з використанням Celery описує, як налаштувати Celery для виконання завдань.
Weblate використовує Celery для виконання завдань у фоновому режимі. Деякі завдання запускаються подіями, а деякі – за розкладом.
Celery Beat використовується для планування завдань, а django-celery-beat використовується для зберігання періодичного розкладу завдань у базі даних. Розклад завдань налаштовується у файлі tasks.py у кожному з застосунків Django.
Завдання виконуються за допомогою кількох черг; маршрутизація налаштовується у settings.py. Черги були розроблені для розділення різних типів робочого навантаження:
celeryЧерга за замовчуванням, де обробляються фонові завдання.
notifyНадсилає електронні листи зі сповіщеннями як для подій у Weblate, так і для автентифікації чи реєстрації. Це окрема черга, яка забезпечує безперебійну доставку електронної пошти, навіть якщо є затримка з виконанням інших завдань.
memoryОновлює записи пам’яті перекладів. Черга оновлення може бути довгою під час імпорту нових рядків, і тривала обробка тут не має великого значення, тому наявність окремої черги дозволяє уникнути блокування інших завдань.
backupЗавдання резервного копіювання не можуть виконуватися паралельно, і один виділений виконавець спрощує це.
translateВідомо, що завдання автоматичного перекладу тривають довго, оскільки вони залучають зовнішні сервіси.