<commit_before># -*- coding: utf-8 -*-
"""
    static_file

    Static File

    :copyright: (c) 2013-2014 by Openlabs Technologies & Consulting (P) Limited
    :license: BSD, see LICENSE for more details.
"""
import os
from io import BytesIO
from datetime import datetime
from urllib2 import unquote

from PIL import Image
import pytz
from nereid.helpers import send_file
from nereid import url_for, route, abort
from jinja2 import Markup
from werkzeug.utils import secure_filename

from trytond.pool import PoolMeta
from trytond.transaction import Transaction

__all__ = ['NereidStaticFile', 'TransformationCommand']
__metaclass__ = PoolMeta

FILTER_MAP = {
    '': Image.NEAREST,
    'n': Image.NEAREST,
    'b': Image.BILINEAR,
    'c': Image.BICUBIC,
    'a': Image.ANTIALIAS,
}


class TransformationCommand(object):
    """
    >>> c = TransformationCommand()
    >>> c.thumbnail(128, 128)
    TransformationCommand(['thumbnail,w_128,h_128,m_n'])
    >>> c.resize(100, 100)
    TransformationCommand(
        ['thumbnail,w_128,h_128,m_n', 'resize,w_100,h_100,m_n']
    )
    >>> c
    TransformationCommand(
        ['thumbnail,w_128,h_128,m_n', 'resize,w_100,h_100,m_n']
    )
    >>> str(c)
    'thumbnail,w_128,h_128,m_n/resize,w_100,h_100,m_n'
    """

    def __init__(self, commands=None):
        if commands is not None:
            self.commands = commands[:]
        else:
            self.commands = []

    def __repr__(self):
        return u'TransformationCommand(%s)' % self.commands

    def __str__(self):
        return '/'.join(self.commands)

    def __unicode__(self):
        return u'/'.join(self.commands)

    def thumbnail(self, width, height, mode='n'):
        """
        Returns a resize command. To understand more about the arguments see
        `pil documentation
        <http://www.pythonware.com/library/pil/handbook/image.htm>`_

        :param width: Width of the image
        :param height: Height og the image
        :param mode: Filter to use
                      * n - NEAREST
                      * l - BILINEAR
                      * c - BICUBIC
                      * a - ANTIALIAS (best quality)
        """
        arguments = ['thumbnail']
        arguments.append('w_%s' % width)
        arguments.append('h_%s' % height)
        if mode:
            arguments.append('m_%s' % mode)

        self.commands.append(','.join(arguments))
        return self

    def resize(self, width, height, mode='n'):
        """
        Returns a resize command. To understand more about the arguments see
        `pil documentation
        <http://www.pythonware.com/library/pil/handbook/image.htm>`_

        :param width: Width of the image
        :param height: Height og the image
        :param mode: Filter to use
                      * n - NEAREST
                      * l - BILINEAR
                      * c - BICUBIC
                      * a - ANTIALIAS (best quality)
        """
        arguments = ['resize']
        arguments.append('w_%s' % width)
        arguments.append('h_%s' % height)
        if mode:
            arguments.append('m_%s' % mode)

        self.commands.append(','.join(arguments))
        return self

    @staticmethod
    def parse_command(command):
        """
        Parse the given commands to a dictionary of command parameters

        :param command: A special command to be parsed
        :return: A tuple of the operation to be done and parameters for it
        """
        command = unquote(unicode(command))

        try:
            operation, params = command.split(',', 1)
        except ValueError:
            abort(404)

        return operation, dict(
            map(lambda arg: arg.split('_'), params.split(','))
        )


class StaticFileTransformationCommand(TransformationCommand):
    """
    A helper class which can be chained to build resizable image
    urls.

    """
    def __init__(self, static_file, extension='png', commands=None):
        """
        :param static_file: ID of static_file or Active Record
        :param extension: File extension to use
        :param commands: A list of commands (optional)
        """
        self.static_file = static_file
        self.extension = extension
        super(StaticFileTransformationCommand, self).__init__(commands)

    def __html__(self):
        return Markup(self.url())

    def url(self, **kwargs):
        """
        Constructs a URL based on the static file and the commands

        .. versionchanged::3.2.0.2

            Supports keyword arguments passed to the url builder

        """
        return url_for(
            'nereid.static.file.transform_static_file',
            active_id=int(self.static_file), commands=unicode(self),
            extension=self.extension, **kwargs
        )


class NereidStaticFile:
    __name__ = "nereid.static.file"

    allowed_operations = ['resize', 'thumbnail']

    @staticmethod
    def thumbnail(image, w=128, h=128, m='n'):<commit_msg>Fetch extension from file_name and then fallback to png<commit_after># -*- coding: utf-8 -*-
"""
    static_file

    Static File

    :copyright: (c) 2013-2014 by Openlabs Technologies & Consulting (P) Limited
    :license: BSD, see LICENSE for more details.
"""
import os
from io import BytesIO
from datetime import datetime
from urllib2 import unquote

from PIL import Image
import pytz
from nereid.helpers import send_file
from nereid import url_for, route, abort
from jinja2 import Markup
from werkzeug.utils import secure_filename

from trytond.pool import PoolMeta
from trytond.transaction import Transaction

__all__ = ['NereidStaticFile', 'TransformationCommand']
__metaclass__ = PoolMeta

FILTER_MAP = {
    '': Image.NEAREST,
    'n': Image.NEAREST,
    'b': Image.BILINEAR,
    'c': Image.BICUBIC,
    'a': Image.ANTIALIAS,
}


class TransformationCommand(object):
    """
    >>> c = TransformationCommand()
    >>> c.thumbnail(128, 128)
    TransformationCommand(['thumbnail,w_128,h_128,m_n'])
    >>> c.resize(100, 100)
    TransformationCommand(
        ['thumbnail,w_128,h_128,m_n', 'resize,w_100,h_100,m_n']
    )
    >>> c
    TransformationCommand(
        ['thumbnail,w_128,h_128,m_n', 'resize,w_100,h_100,m_n']
    )
    >>> str(c)
    'thumbnail,w_128,h_128,m_n/resize,w_100,h_100,m_n'
    """

    def __init__(self, commands=None):
        if commands is not None:
            self.commands = commands[:]
        else:
            self.commands = []

    def __repr__(self):
        return u'TransformationCommand(%s)' % self.commands

    def __str__(self):
        return '/'.join(self.commands)

    def __unicode__(self):
        return u'/'.join(self.commands)

    def thumbnail(self, width, height, mode='n'):
        """
        Returns a resize command. To understand more about the arguments see
        `pil documentation
        <http://www.pythonware.com/library/pil/handbook/image.htm>`_

        :param width: Width of the image
        :param height: Height og the image
        :param mode: Filter to use
                      * n - NEAREST
                      * l - BILINEAR
                      * c - BICUBIC
                      * a - ANTIALIAS (best quality)
        """
        arguments = ['thumbnail']
        arguments.append('w_%s' % width)
        arguments.append('h_%s' % height)
        if mode:
            arguments.append('m_%s' % mode)

        self.commands.append(','.join(arguments))
        return self

    def resize(self, width, height, mode='n'):
        """
        Returns a resize command. To understand more about the arguments see
        `pil documentation
        <http://www.pythonware.com/library/pil/handbook/image.htm>`_

        :param width: Width of the image
        :param height: Height og the image
        :param mode: Filter to use
                      * n - NEAREST
                      * l - BILINEAR
                      * c - BICUBIC
                      * a - ANTIALIAS (best quality)
        """
        arguments = ['resize']
        arguments.append('w_%s' % width)
        arguments.append('h_%s' % height)
        if mode:
            arguments.append('m_%s' % mode)

        self.commands.append(','.join(arguments))
        return self

    @staticmethod
    def parse_command(command):
        """
        Parse the given commands to a dictionary of command parameters

        :param command: A special command to be parsed
        :return: A tuple of the operation to be done and parameters for it
        """
        command = unquote(unicode(command))

        try:
            operation, params = command.split(',', 1)
        except ValueError:
            abort(404)

        return operation, dict(
            map(lambda arg: arg.split('_'), params.split(','))
        )


class StaticFileTransformationCommand(TransformationCommand):
    """
    A helper class which can be chained to build resizable image
    urls.

    """
    def __init__(self, static_file, extension=None, commands=None):
        """
        :param static_file: ID of static_file or Active Record
        :param extension: File extension to use
        :param commands: A list of commands (optional)
        """
        self.static_file = static_file
        self.extension = extension or \
            os.path.splitext(static_file.name)[1][1:] or 'png'
        super(StaticFileTransformationCommand, self).__init__(commands)

    def __html__(self):
        return Markup(self.url())

    def url(self, **kwargs):
        """
        Constructs a URL based on the static file and the commands

        .. versionchanged::3.2.0.2

            Supports keyword arguments passed to the url builder

        """
        return url_for(
            'nereid.static.file.transform_static_file',
            active_id=int(self.static_file), commands=unicode(self),
            extension=self.extension, **kwargs
        )


class NereidStaticFile:
    __name__ = "nereid.static.file"

    allowed_operations = ['resize', 'thumbnail']

    @staticmethod
    def thumbnail(image, w=128, h=128, m='n'):
{'fraction_non_alphanumeric': 0.10830432620586773, 'fraction_numerical': 0.015912481352560914, 'mean_word_length': 2.2522639068564034, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 2, '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': '2918597', 'n_tokens_mistral': 3116, 'n_tokens_neox': 2909, 'n_words': 787}