Example #1
0
    def bulk_create_translaton_memory_entries(self):
        """
        Create Translation Memory entries for:
            - new approved translations
            - updated translations that are approved and don't have a TM entry yet
        """
        translations_to_create_translaton_memory_entries_for = (
            [t for t in self.translations_to_create if t.approved] + list(
                Translation.objects.filter(pk__in=[
                    pk for pk, t in self.translations_to_update.items()
                    if t.approved
                ],
                                           memory_entries__isnull=True)))

        memory_entries = [
            TranslationMemoryEntry(
                source=t.entity.string,
                target=t.string,
                locale_id=t.locale_id,
                entity_id=t.entity.pk,
                translation_id=t.pk,
                project=self.db_project,
            ) for t in translations_to_create_translaton_memory_entries_for
        ]

        TranslationMemoryEntry.objects.bulk_create(memory_entries)
Example #2
0
    def bulk_create_translation_memory_entries(self, valid_translations_pks):
        """
        Create Translation Memory entries for:
            - new approved translations
            - updated translations that are approved and don't have a TM entry yet

        :arg list[int] valid_translations_pks: list of translations (their pks) without errors
        """
        def is_valid(t):
            """
            Verify if a translation should land in the Translation Memory
            """
            return t.approved and t.pk in valid_translations_pks

        translations_to_create_translation_memory_entries_for = (
            [t for t in self.translations_to_create if is_valid(t)] + list(
                Translation.objects.filter(pk__in=[
                    pk for pk, t in self.translations_to_update.items()
                    if is_valid(t)
                ],
                                           memory_entries__isnull=True)))

        memory_entries = [
            TranslationMemoryEntry(
                source=t.tm_source,
                target=t.tm_target,
                locale_id=t.locale_id,
                entity_id=t.entity.pk,
                translation_id=t.pk,
                project=self.db_project,
            ) for t in translations_to_create_translation_memory_entries_for
        ]

        TranslationMemoryEntry.objects.bulk_create(memory_entries)
Example #3
0
 def bulk_create_translations(self):
     Translation.objects.bulk_create(self.translations_to_create)
     memory_entries = [TranslationMemoryEntry(
         source=t.entity.string,
         target=t.string,
         locale_id=t.locale_id,
         entity_id=t.entity.pk,
         translation_id=t.pk
     ) for t in self.translations_to_create if t.plural_form in (None, 0)]
     TranslationMemoryEntry.objects.bulk_create(memory_entries)
Example #4
0
def update_translation_memory(changed_translation_pks, project, locale):
    """Update translation memory for a list of translations."""
    memory_entries = [
        TranslationMemoryEntry(
            source=t.tm_source,
            target=t.tm_target,
            locale=locale,
            entity=t.entity,
            translation=t,
            project=project,
        ) for t in (Translation.objects.filter(pk__in=changed_translation_pks).
                    prefetch_related("entity__resource"))
    ]
    TranslationMemoryEntry.objects.bulk_create(memory_entries)
Example #5
0
def batch_edit_translations(request):
    try:
        l = request.POST['locale']
        action = request.POST['action']
        entity_pks = split_ints(request.POST.get('entities', ''))
    except MultiValueDictKeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    locale = get_object_or_404(Locale, code=l)

    entities = (Entity.objects.filter(
        pk__in=entity_pks).prefetch_resources_translations(locale))

    if not entities.exists():
        return JsonResponse({'count': 0})

    # Batch editing is only available to translators.
    # Check if user has translate permissions for all of the projects in passed entities.
    projects = Project.objects.filter(pk__in=entities.values_list(
        'resource__project__pk', flat=True).distinct())
    for project in projects:
        if not request.user.can_translate(project=project, locale=locale):
            return HttpResponseForbidden(
                "Forbidden: You don't have permission for batch editing")

    translation_pks = set()

    for entity in entities:
        if entity.string_plural == "":
            translation_pks.add(entity.get_translation()['pk'])

        else:
            for plural_form in range(0, locale.nplurals or 1):
                translation_pks.add(entity.get_translation(plural_form)['pk'])

    translation_pks.discard(None)
    translations = Translation.objects.filter(pk__in=translation_pks)
    latest_translation_pk = None
    changed_translation_pks = []

    # Must be executed before translations set changes, which is why
    # we need to force evaluate QuerySets by wrapping them inside list()
    def get_translations_info(translations):
        count = translations.count()
        translated_resources = list(translations.translated_resources(locale))
        changed_entities = list(
            Entity.objects.filter(translation__in=translations).distinct())

        return count, translated_resources, changed_entities

    if action == 'approve':
        translations = translations.filter(approved=False)
        changed_translation_pks = list(
            translations.values_list('pk', flat=True))
        if changed_translation_pks:
            latest_translation_pk = translations.last().pk
        count, translated_resources, changed_entities = get_translations_info(
            translations)
        translations.update(approved=True,
                            approved_user=request.user,
                            approved_date=timezone.now())

    elif action == 'delete':
        count, translated_resources, changed_entities = get_translations_info(
            translations)
        translations.delete()

    elif action == 'replace':
        find = request.POST.get('find')
        replace = request.POST.get('replace')

        try:
            translations, changed_translations = translations.find_and_replace(
                find, replace, request.user)
            changed_translation_pks = [c.pk for c in changed_translations]
            if changed_translation_pks:
                latest_translation_pk = max(changed_translation_pks)
        except Translation.NotAllowed:
            return JsonResponse({
                'error': 'Empty translations not allowed',
            })

        count, translated_resources, changed_entities = get_translations_info(
            translations)

    if count == 0:
        return JsonResponse({'count': 0})

    # Update stats
    for translated_resource in translated_resources:
        translated_resource.calculate_stats(save=False)

    bulk_update(translated_resources,
                update_fields=[
                    'total_strings',
                    'approved_strings',
                    'fuzzy_strings',
                    'translated_strings',
                ])

    project = entity.resource.project
    project.aggregate_stats()
    locale.aggregate_stats()
    ProjectLocale.objects.get(locale=locale, project=project).aggregate_stats()

    # Mark translations as changed
    changed_entities_array = []
    existing = ChangedEntityLocale.objects.values_list('entity',
                                                       'locale').distinct()
    for changed_entity in changed_entities:
        key = (changed_entity.pk, locale.pk)

        # Remove duplicate changes to prevent unique constraint violation
        if not key in existing:
            changed_entities_array.append(
                ChangedEntityLocale(entity=changed_entity, locale=locale))
    ChangedEntityLocale.objects.bulk_create(changed_entities_array)

    # Update latest translation
    if latest_translation_pk:
        Translation.objects.get(
            pk=latest_translation_pk).update_latest_translation()

    # Update translation memory
    memory_entries = [
        TranslationMemoryEntry(
            source=t.entity.string,
            target=t.string,
            locale=locale,
            entity=t.entity,
            translation=t,
            project=project,
        ) for t in Translation.objects.filter(pk__in=changed_translation_pks).
        prefetch_related('entity__resource')
    ]
    TranslationMemoryEntry.objects.bulk_create(memory_entries)

    return JsonResponse({'count': count})