Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
6 changes: 3 additions & 3 deletions documentation/docs/dev/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ Status codes:
### `POST /api/v2/upload/pretranslations/`

Store translations from an uploaded translation file as pretranslations.
This API requires the user to be a member of the `pretranslators` group,
This API requires the user to be a superuser or a member of the `pretranslators` group,
in addition to have translator rights for the target locale and project.

The request body is the same `multipart/form-data` as
Expand Down Expand Up @@ -300,8 +300,8 @@ good one.

The requirements, limits and status codes of
[`POST /api/v2/upload/translations/`](#post-apiv2uploadtranslations) also apply here,
with one difference: the request is rejected with `403` unless the user is a member of
the `pretranslators` group.
with one difference: the request is rejected with `403` unless the user is a superuser
or a member of the `pretranslators` group.

### `POST /api/v2/upload/suggestions/`

Expand Down
3 changes: 2 additions & 1 deletion pontoon/api/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@
from django.utils import timezone

from pontoon.api.models import PersonalAccessToken
from pontoon.base.user_utils import can_pretranslate


class IsPretranslator(BasePermission):
def has_permission(self, request, view):
return request.user.groups.filter(name="pretranslators").exists()
return can_pretranslate(request.user)


class PersonalAccessTokenAuthentication(BaseAuthentication):
Expand Down
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
157 changes: 156 additions & 1 deletion pontoon/batch/actions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from django.db.models import QuerySet
import logging

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

from pontoon.actionlog.models import ActionLog
Expand All @@ -10,11 +13,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 +413,150 @@ 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)
)

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=False,
user=pt_authors[author_key],
value=value,
properties=properties,
)
)

with transaction.atomic():
changed_translations = Translation.objects.bulk_create(translations_to_create)
entity_pks = sorted({t.entity_id for t in changed_translations})
list(
Entity.objects.select_for_update()
.filter(pk__in=entity_pks)
.order_by("pk")
.values_list("pk", flat=True)
)

has_active = set(
Translation.objects.filter(
locale=locale, entity_id__in=entity_pks, active=True
).values_list("entity_id", flat=True)
)

to_activate = [
t.pk for t in changed_translations if t.entity_id not in has_active
]

try:
with transaction.atomic():
Translation.objects.filter(pk__in=to_activate).update(active=True)
except IntegrityError:
for pk in to_activate:
try:
with transaction.atomic():
Translation.objects.filter(pk=pk).update(active=True)
except IntegrityError:
Comment thread
MundiaNderi marked this conversation as resolved.
Resolved
continue

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

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

failed_translation_pks = list(
all_created_qs.exclude(pk__in=syncable_qs).values_list("pk", flat=True)
)

_, translated_resources, changed_entities = utils.get_translations_info(
all_created_qs, locale
)

count, _, _ = utils.get_translations_info(syncable_qs, locale)

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(syncable_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": failed_translation_pks,
"invalid_entity_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 +569,5 @@ def copy_translation_from_locale(
"reject": reject_translations,
"replace": replace_translations,
"copy_from_locale": copy_translation_from_locale,
"pretranslate": pretranslate_translations,
}
1 change: 1 addition & 0 deletions pontoon/batch/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class BatchActionsForm(forms.Form):
("reject", "reject"),
("replace", "replace"),
("copy_from_locale", "copy_from_locale"),
("pretranslate", "pretranslate"),
]
)
entities = forms.CharField(required=False)
Expand Down
60 changes: 60 additions & 0 deletions pontoon/batch/tasks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
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)

tr_pks = [tr.pk for tr in action_status["translated_resources"]]
TranslatedResource.objects.filter(pk__in=tr_pks).calculate_stats()

if action_status["count"] > 0:
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", [])
)
+ len(action_status.get("invalid_entity_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)
Loading
Loading