<commit_before>from django.conf import settings
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic.base import View

from wagtail.admin.auth import PermissionPolicyChecker
from wagtail.admin.forms.search import SearchForm
from wagtail.admin.modal_workflow import render_modal_workflow
from wagtail.admin.models import popular_tags_for_model
from wagtail.core import hooks
from wagtail.images import get_image_model
from wagtail.images.formats import get_image_format
from wagtail.images.forms import ImageInsertionForm, get_image_form
from wagtail.images.permissions import permission_policy
from wagtail.search import index as search_index


permission_checker = PermissionPolicyChecker(permission_policy)

CHOOSER_PAGE_SIZE = getattr(settings, 'WAGTAILIMAGES_CHOOSER_PAGE_SIZE', 12)


def get_chooser_js_data():
    """construct context variables needed by the chooser JS"""
    return {
        'step': 'chooser',
        'error_label': _("Server Error"),
        'error_message': _("Report this error to your webmaster with the following information:"),
        'tag_autocomplete_url': reverse('wagtailadmin_tag_autocomplete'),
    }


def get_image_result_data(image):
    """
    helper function: given an image, return the json data to pass back to the
    image chooser panel
    """
    preview_image = image.get_rendition('max-165x165')

    return {
        'id': image.id,
        'edit_link': reverse('wagtailimages:edit', args=(image.id,)),
        'title': image.title,
        'preview': {
            'url': preview_image.url,
            'width': preview_image.width,
            'height': preview_image.height,
        }
    }


def get_chooser_context(request):
    """Helper function to return common template context variables for the main chooser view"""

    collections = permission_policy.collections_user_has_permission_for(
        request.user, 'choose'
    )
    if len(collections) < 2:
        collections = None

    return {
        'searchform': SearchForm(),
        'is_searching': False,
        'query_string': None,
        'will_select_format': request.GET.get('select_format'),
        'popular_tags': popular_tags_for_model(get_image_model()),
        'collections': collections,
    }


class ChooseView(View):
    def get(self, request):
        Image = get_image_model()

        if permission_policy.user_has_permission(request.user, 'add'):
            ImageForm = get_image_form(Image)
            uploadform = ImageForm(user=request.user, prefix='image-chooser-upload')
        else:
            uploadform = None

        images = permission_policy.instances_user_has_any_permission_for(
            request.user, ['choose']
        ).order_by('-created_at')

        # allow hooks to modify the queryset
        for hook in hooks.get_hooks('construct_image_chooser_queryset'):
            images = hook(images, request)

        if (
            'q' in request.GET or 'p' in request.GET or 'tag' in request.GET
            or 'collection_id' in request.GET
        ):
            # this request is triggered from search, pagination or 'popular tags';
            # we will just render the results.html fragment
            collection_id = request.GET.get('collection_id')
            if collection_id:
                images = images.filter(collection=collection_id)

            searchform = SearchForm(request.GET)
            if searchform.is_valid():
                q = searchform.cleaned_data['q']

                images = images.search(q)
                is_searching = True
            else:
                is_searching = False
                q = None

                tag_name = request.GET.get('tag')
                if tag_name:
                    images = images.filter(tags__name=tag_name)

            # Pagination
            paginator = Paginator(images, per_page=CHOOSER_PAGE_SIZE)
            images = paginator.get_page(request.GET.get('p'))

            return TemplateResponse(request, "wagtailimages/chooser/results.html", {
                'images': images,
                'is_searching': is_searching,
                'query_string': q,
                'will_select_format': request.GET.get('select_format')
            })
        else:
            paginator = Paginator(images, per_page=CHOOSER_PAGE_SIZE)
            images = paginator.get_page(request.GET.get('p'))

            context = get_chooser_context(request)
            context.update({
                'images': images,
                'uploadform': uploadform,
            })
            return render_modal_workflow(
                request, 'wagtailimages/chooser/chooser.html', None, context,
                json_data=get_chooser_js_data()
            )


def image_chosen(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    return render_modal_workflow(
        request, None, None,
        None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)}
    )
<commit_msg>Split response rendering into its own method<commit_after>from django.conf import settings
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404
from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.translation import gettext as _
from django.views.generic.base import View

from wagtail.admin.auth import PermissionPolicyChecker
from wagtail.admin.forms.search import SearchForm
from wagtail.admin.modal_workflow import render_modal_workflow
from wagtail.admin.models import popular_tags_for_model
from wagtail.core import hooks
from wagtail.images import get_image_model
from wagtail.images.formats import get_image_format
from wagtail.images.forms import ImageInsertionForm, get_image_form
from wagtail.images.permissions import permission_policy
from wagtail.search import index as search_index


permission_checker = PermissionPolicyChecker(permission_policy)

CHOOSER_PAGE_SIZE = getattr(settings, 'WAGTAILIMAGES_CHOOSER_PAGE_SIZE', 12)


def get_chooser_js_data():
    """construct context variables needed by the chooser JS"""
    return {
        'step': 'chooser',
        'error_label': _("Server Error"),
        'error_message': _("Report this error to your webmaster with the following information:"),
        'tag_autocomplete_url': reverse('wagtailadmin_tag_autocomplete'),
    }


def get_image_result_data(image):
    """
    helper function: given an image, return the json data to pass back to the
    image chooser panel
    """
    preview_image = image.get_rendition('max-165x165')

    return {
        'id': image.id,
        'edit_link': reverse('wagtailimages:edit', args=(image.id,)),
        'title': image.title,
        'preview': {
            'url': preview_image.url,
            'width': preview_image.width,
            'height': preview_image.height,
        }
    }


def get_chooser_context(request):
    """Helper function to return common template context variables for the main chooser view"""

    collections = permission_policy.collections_user_has_permission_for(
        request.user, 'choose'
    )
    if len(collections) < 2:
        collections = None

    return {
        'searchform': SearchForm(),
        'is_searching': False,
        'query_string': None,
        'will_select_format': request.GET.get('select_format'),
        'popular_tags': popular_tags_for_model(get_image_model()),
        'collections': collections,
    }


class ChooseView(View):
    def get(self, request):
        Image = get_image_model()

        if permission_policy.user_has_permission(request.user, 'add'):
            ImageForm = get_image_form(Image)
            self.uploadform = ImageForm(user=request.user, prefix='image-chooser-upload')
        else:
            self.uploadform = None

        images = permission_policy.instances_user_has_any_permission_for(
            request.user, ['choose']
        ).order_by('-created_at')

        # allow hooks to modify the queryset
        for hook in hooks.get_hooks('construct_image_chooser_queryset'):
            images = hook(images, request)

        if (
            'q' in request.GET or 'p' in request.GET or 'tag' in request.GET
            or 'collection_id' in request.GET
        ):
            # this request is triggered from search, pagination or 'popular tags';
            # we will just render the results.html fragment
            collection_id = request.GET.get('collection_id')
            if collection_id:
                images = images.filter(collection=collection_id)

            searchform = SearchForm(request.GET)
            if searchform.is_valid():
                self.q = searchform.cleaned_data['q']

                images = images.search(self.q)
                self.is_searching = True
            else:
                self.is_searching = False
                self.q = None

                tag_name = request.GET.get('tag')
                if tag_name:
                    images = images.filter(tags__name=tag_name)

        # Pagination
        paginator = Paginator(images, per_page=CHOOSER_PAGE_SIZE)
        self.images = paginator.get_page(request.GET.get('p'))
        return self.render_to_response()

    def render_to_response(self):
        if (
            'q' in self.request.GET or 'p' in self.request.GET or 'tag' in self.request.GET
            or 'collection_id' in self.request.GET
        ):
            return TemplateResponse(self.request, "wagtailimages/chooser/results.html", {
                'images': self.images,
                'is_searching': self.is_searching,
                'query_string': self.q,
                'will_select_format': self.request.GET.get('select_format')
            })
        else:
            context = get_chooser_context(self.request)
            context.update({
                'images': self.images,
                'uploadform': self.uploadform,
            })
            return render_modal_workflow(
                self.request, 'wagtailimages/chooser/chooser.html', None, context,
                json_data=get_chooser_js_data()
            )


def image_chosen(request, image_id):
    image = get_object_or_404(get_image_model(), id=image_id)

    return render_modal_workflow(
        request, None, None,
        None, json_data={'step': 'image_chosen', 'result': get_image_result_data(image)}
    )

{'fraction_non_alphanumeric': 0.0909262938783234, 'fraction_numerical': 0.002838489923360772, 'mean_word_length': 2.6298076923076925, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1056414', 'n_tokens_mistral': 3041, 'n_tokens_neox': 2929, 'n_words': 679}