Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions pontoon/base/user_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,8 @@ def can_translate(user: User, project: "Project", locale: "Locale") -> bool:
return user.has_perm("base.can_translate_project_locale", project_locale)

return user.has_perm("base.can_translate_locale", locale)


def can_pretranslate(user: User) -> bool:
"""Check if user has suitable permissions to manually trigger batch pretranslation."""
return user.is_superuser or user.groups.filter(name="pretranslators").exists()
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved
129 changes: 128 additions & 1 deletion pontoon/batch/actions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from django.db.models import QuerySet
import logging

from django.db.models import Q, QuerySet
from django.utils import timezone

from pontoon.actionlog.models import ActionLog
Expand All @@ -10,11 +12,18 @@
TranslationMemoryEntry,
)
from pontoon.base.models.translation import TranslationQuerySet
from pontoon.base.user_utils import get_pretranslation_authors
from pontoon.batch import utils
from pontoon.checks.libraries import run_checks
from pontoon.checks.utils import bulk_run_checks
from pontoon.messaging.notifications import send_badge_notification
from pontoon.pretranslation.pretranslate import get_pretranslation
from pontoon.translations.utils import parse_source_string_to_json


logger = logging.getLogger(__name__)


def batch_action_template(form, user, translations, locale):
"""Empty batch action, does nothing, only used for documentation.

Expand Down Expand Up @@ -403,6 +412,123 @@ def copy_translation_from_locale(
}


def pretranslate_translations(user, locale: Locale, entities: QuerySet[Entity]):
"""
Enable teams to pretranslate an entire project or a subset of strings on projects
for which pretranslation is not enabled by the admins.
"""
pt_authors = get_pretranslation_authors()

excluded_entity_pks = set(
Translation.objects.filter(locale=locale, entity__in=entities)
.filter(Q(approved=True) | Q(user__in=pt_authors.values()))
.values_list("entity__pk", flat=True)
)

already_active_entity_pks = set(
Translation.objects.filter(
locale=locale,
entity__in=entities,
active=True,
).values_list("entity__pk", flat=True)
)

eligible_entities = entities.exclude(pk__in=excluded_entity_pks)

translations_to_create = []

invalid_entity_pks = []

for entity in eligible_entities:
try:
pretranslation = get_pretranslation(entity, locale)
except ValueError as e:
logger.info(f"Pretranslation error for entity {entity.pk}: {e!r}")
invalid_entity_pks.append(entity.pk)
continue

failed_checks = run_checks(
entity, locale.code, pretranslation[0], use_tt_checks=False
)

if failed_checks:
try:
pretranslation = get_pretranslation(
entity, locale, preserve_placeables=True
)
except ValueError as e:
logger.info(f"Pretranslation error for entity {entity.pk}: {e!r}")
invalid_entity_pks.append(entity.pk)
continue

string, author_key = pretranslation

try:
_, value, properties = parse_source_string_to_json(
entity.resource.format, string, locale.plural_catchall
)
except ValueError as e:
logger.error(
f"Unparsable pretranslation for entity {entity.pk}: {e!r}: {string!r}"
)
invalid_entity_pks.append(entity.pk)
continue

translations_to_create.append(
Translation(
locale=locale,
entity=entity,
string=string,
approved=False,
rejected=False,
fuzzy=False,
pretranslated=True,
active=entity.pk not in already_active_entity_pks,
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved
user=pt_authors[author_key],
value=value,
properties=properties,
)
)

changed_translations = Translation.objects.bulk_create(translations_to_create)
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved

translation_pks = {t.pk for t in changed_translations}
bulk_run_checks(Translation.objects.for_checks().filter(pk__in=translation_pks))

changed_translations_qs = Translation.objects.filter(
pk__in=translation_pks, errors__isnull=True, warnings__isnull=True
)

count, translated_resources, changed_entities = utils.get_translations_info(
changed_translations_qs, locale
)
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved

actions_to_log = [
ActionLog(
action_type=ActionLog.ActionType.TRANSLATION_CREATED,
performed_by=t.user,
translation=t,
)
for t in changed_translations
]

ActionLog.objects.bulk_create(actions_to_log)

changed_translation_pks = list(changed_translations_qs.values_list("pk", flat=True))

return {
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved
"count": count,
"translated_resources": translated_resources,
"changed_entities": changed_entities,
"latest_translation_pk": max(changed_translation_pks)
if changed_translation_pks
else None,
"changed_translation_pks": changed_translation_pks,
"invalid_translation_pks": invalid_entity_pks,
"badge_update": {},
}


"""A map of action names to functions.

The keys define the available batch actions in the `batch_edit_translations`
Expand All @@ -415,4 +541,5 @@ def copy_translation_from_locale(
"reject": reject_translations,
"replace": replace_translations,
"copy_from_locale": copy_translation_from_locale,
"pretranslate": pretranslate_translations,
}
5 changes: 5 additions & 0 deletions pontoon/batch/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ class BatchActionsForm(forms.Form):
("reject", "reject"),
("replace", "replace"),
("copy_from_locale", "copy_from_locale"),
("pretranslate", "pretranslate"),
]
)
entities = forms.CharField(required=False)
find = forms.CharField(required=False)
replace = forms.CharField(required=False)
other_locale = forms.CharField(required=False)
pretranslate = forms.CharField(required=False)
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved

def clean_entities(self):
return utils.split_ints(self.cleaned_data["entities"])
Expand All @@ -42,3 +44,6 @@ def clean_replace(self):

def clean_other_locale(self):
return self.decode_field("other_locale")

def clean_pretranslate(self):
return self.decode_field("pretranslate")
59 changes: 59 additions & 0 deletions pontoon/batch/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import logging

from celery import shared_task

from django.core.cache import cache

from pontoon.base.models import Entity, Locale, TranslatedResource, Translation, User
from pontoon.base.tasks import PontoonTask
from pontoon.batch.actions import pretranslate_translations


log = logging.getLogger(__name__)


@shared_task(base=PontoonTask, name="batch_pretranslate")
def batch_pretranslate_task(user_pk, locale_pk, entity_pks):
lock_name = f"batch_pretranslate_{locale_pk}"
try:
user = User.objects.get(pk=user_pk)
locale = Locale.objects.get(pk=locale_pk)
entities = Entity.objects.filter(pk__in=entity_pks)
action_status = pretranslate_translations(user, locale, entities)

if action_status["count"] > 0:
tr_pks = [tr.pk for tr in action_status["translated_resources"]]
TranslatedResource.objects.filter(pk__in=tr_pks).calculate_stats()
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved

Translation.objects.filter(
pk__in=action_status["changed_translation_pks"]
).bulk_mark_changed()

changed_entity_pks = [e.pk for e in action_status["changed_entities"]]
for e in Entity.objects.filter(
pk__in=changed_entity_pks,
resource__project__slug="terminology",
):
e.reset_term_translation(locale)

if action_status["latest_translation_pk"]:
Translation.objects.get(
pk=action_status["latest_translation_pk"]
).update_latest_translation()

cache.set(
f"{lock_name}_result",
{
"count": action_status["count"],
"invalid_translation_count": len(
action_status.get("invalid_translation_pks", [])
),
},
timeout=3600,
)
except Exception:
log.exception("Batch pretranslation failed")
cache.set(f"{lock_name}_result", {"error": True}, timeout=3600)
raise
finally:
cache.delete(lock_name)
132 changes: 130 additions & 2 deletions pontoon/batch/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
from unittest.mock import patch

import pytest

from fluent.syntax import FluentParser, FluentSerializer

from pontoon.base.models import Locale, Translation
from pontoon.batch.actions import copy_translation_from_locale
from pontoon.base.models import Entity, Locale, Translation
from pontoon.base.user_utils import get_pretranslation_authors
from pontoon.batch.actions import (
copy_translation_from_locale,
pretranslate_translations,
)
from pontoon.batch.utils import (
find_and_replace,
ftl_find_and_replace,
Expand Down Expand Up @@ -172,3 +178,125 @@ def test_copy_from_another_locale_copies_all_strings():
).count()
== 1
)


@pytest.mark.django_db
@patch("pontoon.batch.actions.bulk_run_checks")
@patch("pontoon.batch.actions.get_pretranslation")
def test_pretranslate_translations_skips_approved_includes_suggestions(
get_pretranslation_mock,
bulk_run_checks_mock,
):
"""
Pretranslation is skipped for entities with an approved translation,
but generated for entities with only a pending suggestion or no
translation at all.
"""

get_pretranslation_mock.return_value = ("key = pretranslated value", "gt")

project = ProjectFactory(slug="project4", name="Project4")
resource = ResourceFactory(project=project, path="resource.ftl", format="fluent")
entity_approved = EntityFactory(resource=resource, string="key1 = value1")
entity_suggestion = EntityFactory(resource=resource, string="key2 = value2")
entity_untranslated = EntityFactory(resource=resource, string="key3 = value3")
locale = Locale.objects.get(code="en-ZA")
user = UserFactory()

TranslationFactory(
entity=entity_approved,
locale=locale,
string="already approved",
approved=True,
active=True,
)

TranslationFactory(
entity=entity_suggestion,
locale=locale,
string="pending suggestion",
approved=False,
active=True,
)

entities = Entity.objects.filter(
pk__in=[entity_approved.pk, entity_suggestion.pk, entity_untranslated.pk]
)

result = pretranslate_translations(user, locale, entities)

# entity_approved: skipped entirely, no new translation created
assert not Translation.objects.filter(
entity=entity_approved, string="key = pretranslated value"
).exists()

# entity_suggestion: pretranslated even though a suggestion already exists;
# existing suggestion is still active, so the new one is not
assert Translation.objects.filter(
entity=entity_suggestion,
string="key = pretranslated value",
pretranslated=True,
active=False,
).exists()

# entity_untranslated: pretranslated and active, since nothing existed before
assert Translation.objects.filter(
entity=entity_untranslated,
string="key = pretranslated value",
pretranslated=True,
active=True,
).exists()

assert result["count"] == 2


@pytest.mark.django_db
@patch("pontoon.batch.actions.get_pretranslation")
def test_pretranslate_translations_skips_existing_pretranslations(
get_pretranslation_mock,
):
get_pretranslation_mock.return_value = ("key = pretranslated value", "gt")

project = ProjectFactory(slug="project5", name="Project5")
resource = ResourceFactory(project=project, path="resource.ftl", format="fluent")
entity = EntityFactory(resource=resource, string="key1 = value1")
locale = Locale.objects.get(code="en-ZA")
gt_user = get_pretranslation_authors()["gt"]

TranslationFactory(
entity=entity,
locale=locale,
string="existing pretranslation",
pretranslated=True,
user=gt_user,
)

result = pretranslate_translations(
UserFactory(), locale, Entity.objects.filter(pk=entity.pk)
)

assert Translation.objects.filter(entity=entity).count() == 1
assert result["count"] == 0


@pytest.mark.django_db
@patch("pontoon.batch.actions.run_checks")
@patch("pontoon.batch.actions.get_pretranslation")
def test_pretranslate_translations_retries_on_failed_checks(
get_pretranslation_mock,
run_checks_mock,
):
get_pretranslation_mock.return_value = ("key = pretranslated value", "gt")
run_checks_mock.return_value = {"clWarnings": ["some warning"]}

project = ProjectFactory(slug="project6", name="Project6")
resource = ResourceFactory(project=project, path="resource.ftl", format="fluent")
entity = EntityFactory(resource=resource, string="key1 = value1")
locale = Locale.objects.get(code="en-ZA")

pretranslate_translations(
UserFactory(), locale, Entity.objects.filter(pk=entity.pk)
)

assert get_pretranslation_mock.call_count == 2
get_pretranslation_mock.assert_called_with(entity, locale, preserve_placeables=True)
Loading
Loading