<commit_before>from abstract import layer, _activate, _dropout
import numpy
import numpy.random as rng
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams

class rotate_layer (layer):
    """
    This is a rotate layer. This takes a layer and an angle (rotation normalized in [0,1]) as input
    and rotates the batch of images by the specified rotation parameter.

    Args:
        input: An input ``theano.tensor`` variable. Even ``theano.shared`` will work as long as they
               are in the following shape ``mini_batch_size, height, width, channels``
        verbose: similar to the rest of the toolbox.
        input_shape: ``(mini_batch_size, input_size)``
        angle: value from [0,1]
        borrow: ``theano`` borrow, typicall ``True``.
        input_params: Supply params or initializations from a pre-trained system.
    """

    def __init__ (self,
                  input,
                  input_shape,
                  id,
                  angle = None,
                  borrow = True,
                  verbose = 2 ):
        super(rotate_layer,self).__init__(id = id, type = 'rotate', verbose = verbose)
        srng = RandomStreams(rng.randint(1,2147462468), use_cuda=None)
        if verbose >= 3:
            print "... Creating rotate layer"

        if len(input_shape) == 4:
            if verbose >= 3:
                print "... Creating the rotate layer"

            if angle is None:
                angle = srng.uniform(size = input_shape[0], low =limits[0], high =limits[1],
                                                dtype = theano.config.floatX )

            angle = angle.dimshuffle(0,'x')
            theta = numpy.zeros((input_shape[0],2,3),dtype='float32')
            theta[:,0,0] = numpy.cos(angle[:,0]*180)
            theta[:,0,1] = -numpy.sin(angle[:,0]*180)
            theta[:,1,0] = numpy.sin(angle[:,0]*180)
            theta[:,1,1] = numpy.cos(angle[:,0]*180)
            theta = theta.reshape((input_shape[0], 6))

            self.output = self._transform_affine(theta, input)
            import pdb
            pdb.set_trace()
            self.output_shape = input_shape
            self.angle = angle

    def _transform_affine(self, theta, input):
        num_batch, num_channels, height, width = input.shape
        theta = T.reshape(theta, (-1, 2, 3))

        # grid of (x_t, y_t, 1)
        out_height = T.cast(height, 'int64')
        out_width = T.cast(width, 'int64')
        grid = _meshgrid(out_height, out_width)

        # Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)
        T_g = T.dot(theta, grid)
        x_s = T_g[:, 0]
        y_s = T_g[:, 1]
        x_s_flat = x_s.flatten()
        y_s_flat = y_s.flatten()

        # dimshuffle input to  (bs, height, width, channels)
        input_dim = input.dimshuffle(0, 2, 3, 1)
        input_transformed = _interpolate(
            input_dim, x_s_flat, y_s_flat,
            out_height, out_width)

        output = T.reshape(
            input_transformed, (num_batch, out_height, out_width, num_channels))
        output = output.dimshuffle(0, 3, 1, 2)  # dimshuffle to conv format
        return output

    def _interpolate(self, im, x, y, out_height, out_width):
        # *_f are floats
        num_batch, height, width, channels = im.shape
        height_f = T.cast(height, theano.config.floatX)
        width_f = T.cast(width, theano.config.floatX)

        # clip coordinates to [-1, 1]
        x = T.clip(x, -1, 1)
        y = T.clip(y, -1, 1)

        # scale coordinates from [-1, 1] to [0, width/height - 1]
        x = (x + 1) / 2 * (width_f - 1)
        y = (y + 1) / 2 * (height_f - 1)

        # obtain indices of the 2x2 pixel neighborhood surrounding the coordinates;
        # we need those in floatX for interpolation and in int64 for indexing. for
        # indexing, we need to take care they do not extend past the image.
        x0_f = T.floor(x)
        y0_f = T.floor(y)
        x1_f = x0_f + 1
        y1_f = y0_f + 1
        x0 = T.cast(x0_f, 'int64')
        y0 = T.cast(y0_f, 'int64')
        x1 = T.cast(T.minimum(x1_f, width_f - 1), 'int64')
        y1 = T.cast(T.minimum(y1_f, height_f - 1), 'int64')

        # The input is [num_batch, height, width, channels]. We do the lookup in
        # the flattened input, i.e [num_batch*height*width, channels]. We need
        # to offset all indices to match the flat version
        dim2 = width
        dim1 = width*height
        base = T.repeat(
            T.arange(num_batch, dtype='int64')*dim1, out_height*out_width)
        base_y0 = base + y0*dim2
        base_y1 = base + y1*dim2
        idx_a = base_y0 + x0
        idx_b = base_y1 + x0
        idx_c = base_y0 + x1
        idx_d = base_y1 + x1

        # use indices to lookup pixels for all samples
        im_flat = im.reshape((-1, channels))
        Ia = im_flat[idx_a]
        Ib = im_flat[idx_b]
        Ic = im_flat[idx_c]
        Id = im_flat[idx_d]

        # calculate interpolated values
        wa = ((x1_f-x) * (y1_f-y)).dimshuffle(0, 'x')
        wb = ((x1_f-x) * (y-y0_f)).dimshuffle(0, 'x')
        wc = ((x-x0_f) * (y1_f-y)).dimshuffle(0, 'x')
        wd = ((x-x0_f) * (y-y0_f)).dimshuffle(0, 'x')
        output = T.sum([wa*Ia, wb*Ib, wc*Ic, wd*Id], axis=0)
        return output

    def _linspace(self, start, stop, num):
        # Theano linspace. Behaves similar to np.linspace
        start = T.cast(start, theano.config.floatX)
        stop = T.cast(stop, theano.config.floatX)
        num = T.cast(num, theano.config.floatX)
        step = (stop-start)/(num-1)
        return T.arange(num, dtype=theano.config.floatX)*step+start

    def _meshgrid(self, height, width):
        # This function is the grid generator.
        # It is equivalent to the following numpy code:
        #  x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
        #                         np.linspace(-1, 1, height))
        #  ones = np.ones(np.prod(x_t.shape))
        #  grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
        # It is implemented in Theano instead to support symbolic grid sizes.
        # Note: If the image size is known at layer construction time, we could
        # compute the meshgrid offline in numpy instead of doing it dynamically
        # in Theano. However, it hardly affected performance when we tried.
        x_t = T.dot(T.ones((height, 1)),
                    _linspace(-1.0, 1.0, width).dimshuffle('x', 0))
        y_t = T.dot(_linspace(-1.0, 1.0, height).dimshuffle(0, 'x'),
                    T.ones((1, width)))

        x_t_flat = x_t.reshape((1, -1))
        y_t_flat = y_t.reshape((1, -1))
        ones = T.ones_like(x_t_flat)
        grid = T.concatenate([x_t_flat, y_t_flat, ones], axis=0)
        return grid

class dropout_rotate_layer (rotate_layer):
    """
    This class is the typical dropout neural hidden layer and batch normalization layer. Called
    by the ``add_layer`` method in network class.

    Args:
        input: An input ``theano.tensor`` variable. Even ``theano.shared`` will work as long as they
               are in the following shape ``mini_batch_size, height, width, channels``
        verbose: similar to the rest of the toolbox.
        num_neurons: number of neurons in the layer
        input_shape: ``(mini_batch_size, input_size)``
        batch_norm: If provided will be used, default is ``False``.
        rng: typically ``numpy.random``.
        borrow: ``theano`` borrow, typicall ``True``.
        dropout_rate: ``0.5`` is the default.

    Notes:
        Use ``dropout_rotate_layer.output`` and ``dropout_rotate_layer.output_shape`` from
        this class. ``L1`` and ``L2`` are also public and can also can be used for regularization.
        The class also has in public ``w``, ``b`` and ``alpha``
        which are also a list in ``params``, another property of this class.
    """
    def __init__ (self,
                  input,
                  input_shape,
                  id,
                  rng = None,
                  dropout_rate = 0.5,
                  angle = None,
                  borrow = True,
                  verbose = 2):

        if verbose >= 3:
            print "... set up the dropout rotate layer"
        import pdb
        pdb.set_trace()
        if rng is None:
            rng = numpy.random
        super(dropout_rotate_layer, self).__init__ (
                                        input = input,
                                        input_shape = input_shape,
                                        id = id,
                                        borrow = borrow,
                                        verbose = verbose
                                        )
        if not dropout_rate == 0:
            self.output = _dropout(rng = rng,
                                params = self.output,
                                dropout_rate = dropout_rate)
        self.dropout_rate = dropout_rate
        if verbose >=3:
            print "... Dropped out"

if __name__ == '__main__':
    pass  <commit_msg>transform.py fix<commit_after>from abstract import layer, _activate, _dropout
import numpy
import numpy.random as rng
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams

class rotate_layer (layer):
    """
    This is a rotate layer. This takes a layer and an angle (rotation normalized in [0,1]) as input
    and rotates the batch of images by the specified rotation parameter.

    Args:
        input: An input ``theano.tensor`` variable. Even ``theano.shared`` will work as long as they
               are in the following shape ``mini_batch_size, height, width, channels``
        verbose: similar to the rest of the toolbox.
        input_shape: ``(mini_batch_size, input_size)``
        angle: value from [0,1]
        borrow: ``theano`` borrow, typicall ``True``.
        input_params: Supply params or initializations from a pre-trained system.
    """

    def __init__ (self,
                  input,
                  input_shape,
                  id,
                  angle = None,
                  borrow = True,
                  verbose = 2 ):
        super(rotate_layer,self).__init__(id = id, type = 'rotate', verbose = verbose)
        srng = RandomStreams(rng.randint(1,2147462468), use_cuda=None)
        if verbose >= 3:
            print "... Creating rotate layer"

        if len(input_shape) == 4:
            if verbose >= 3:
                print "... Creating the rotate layer"

            if angle is None:
                angle = srng.uniform(size = input_shape[0], low =limits[0], high =limits[1],
                                                dtype = theano.config.floatX )

            angle = angle.dimshuffle(0,'x')
            theta = numpy.zeros((input_shape[0],2,3),dtype='float32')
            import pdb
            pdb.set_trace()
            theta[:,0,0] = numpy.cos(angle[:,0]*180)
            theta[:,0,1] = -numpy.sin(angle[:,0]*180)
            theta[:,1,0] = numpy.sin(angle[:,0]*180)
            theta[:,1,1] = numpy.cos(angle[:,0]*180)
            theta = theta.reshape((input_shape[0], 6))

            self.output = self._transform_affine(theta, input)
            import pdb
            pdb.set_trace()
            self.output_shape = input_shape
            self.angle = angle

    def _transform_affine(self, theta, input):
        num_batch, num_channels, height, width = input.shape
        theta = T.reshape(theta, (-1, 2, 3))

        # grid of (x_t, y_t, 1)
        out_height = T.cast(height, 'int64')
        out_width = T.cast(width, 'int64')
        grid = _meshgrid(out_height, out_width)

        # Transform A x (x_t, y_t, 1)^T -> (x_s, y_s)
        T_g = T.dot(theta, grid)
        x_s = T_g[:, 0]
        y_s = T_g[:, 1]
        x_s_flat = x_s.flatten()
        y_s_flat = y_s.flatten()

        # dimshuffle input to  (bs, height, width, channels)
        input_dim = input.dimshuffle(0, 2, 3, 1)
        input_transformed = _interpolate(
            input_dim, x_s_flat, y_s_flat,
            out_height, out_width)

        output = T.reshape(
            input_transformed, (num_batch, out_height, out_width, num_channels))
        output = output.dimshuffle(0, 3, 1, 2)  # dimshuffle to conv format
        return output

    def _interpolate(self, im, x, y, out_height, out_width):
        # *_f are floats
        num_batch, height, width, channels = im.shape
        height_f = T.cast(height, theano.config.floatX)
        width_f = T.cast(width, theano.config.floatX)

        # clip coordinates to [-1, 1]
        x = T.clip(x, -1, 1)
        y = T.clip(y, -1, 1)

        # scale coordinates from [-1, 1] to [0, width/height - 1]
        x = (x + 1) / 2 * (width_f - 1)
        y = (y + 1) / 2 * (height_f - 1)

        # obtain indices of the 2x2 pixel neighborhood surrounding the coordinates;
        # we need those in floatX for interpolation and in int64 for indexing. for
        # indexing, we need to take care they do not extend past the image.
        x0_f = T.floor(x)
        y0_f = T.floor(y)
        x1_f = x0_f + 1
        y1_f = y0_f + 1
        x0 = T.cast(x0_f, 'int64')
        y0 = T.cast(y0_f, 'int64')
        x1 = T.cast(T.minimum(x1_f, width_f - 1), 'int64')
        y1 = T.cast(T.minimum(y1_f, height_f - 1), 'int64')

        # The input is [num_batch, height, width, channels]. We do the lookup in
        # the flattened input, i.e [num_batch*height*width, channels]. We need
        # to offset all indices to match the flat version
        dim2 = width
        dim1 = width*height
        base = T.repeat(
            T.arange(num_batch, dtype='int64')*dim1, out_height*out_width)
        base_y0 = base + y0*dim2
        base_y1 = base + y1*dim2
        idx_a = base_y0 + x0
        idx_b = base_y1 + x0
        idx_c = base_y0 + x1
        idx_d = base_y1 + x1

        # use indices to lookup pixels for all samples
        im_flat = im.reshape((-1, channels))
        Ia = im_flat[idx_a]
        Ib = im_flat[idx_b]
        Ic = im_flat[idx_c]
        Id = im_flat[idx_d]

        # calculate interpolated values
        wa = ((x1_f-x) * (y1_f-y)).dimshuffle(0, 'x')
        wb = ((x1_f-x) * (y-y0_f)).dimshuffle(0, 'x')
        wc = ((x-x0_f) * (y1_f-y)).dimshuffle(0, 'x')
        wd = ((x-x0_f) * (y-y0_f)).dimshuffle(0, 'x')
        output = T.sum([wa*Ia, wb*Ib, wc*Ic, wd*Id], axis=0)
        return output

    def _linspace(self, start, stop, num):
        # Theano linspace. Behaves similar to np.linspace
        start = T.cast(start, theano.config.floatX)
        stop = T.cast(stop, theano.config.floatX)
        num = T.cast(num, theano.config.floatX)
        step = (stop-start)/(num-1)
        return T.arange(num, dtype=theano.config.floatX)*step+start

    def _meshgrid(self, height, width):
        # This function is the grid generator.
        # It is equivalent to the following numpy code:
        #  x_t, y_t = np.meshgrid(np.linspace(-1, 1, width),
        #                         np.linspace(-1, 1, height))
        #  ones = np.ones(np.prod(x_t.shape))
        #  grid = np.vstack([x_t.flatten(), y_t.flatten(), ones])
        # It is implemented in Theano instead to support symbolic grid sizes.
        # Note: If the image size is known at layer construction time, we could
        # compute the meshgrid offline in numpy instead of doing it dynamically
        # in Theano. However, it hardly affected performance when we tried.
        x_t = T.dot(T.ones((height, 1)),
                    _linspace(-1.0, 1.0, width).dimshuffle('x', 0))
        y_t = T.dot(_linspace(-1.0, 1.0, height).dimshuffle(0, 'x'),
                    T.ones((1, width)))

        x_t_flat = x_t.reshape((1, -1))
        y_t_flat = y_t.reshape((1, -1))
        ones = T.ones_like(x_t_flat)
        grid = T.concatenate([x_t_flat, y_t_flat, ones], axis=0)
        return grid

class dropout_rotate_layer (rotate_layer):
    """
    This class is the typical dropout neural hidden layer and batch normalization layer. Called
    by the ``add_layer`` method in network class.

    Args:
        input: An input ``theano.tensor`` variable. Even ``theano.shared`` will work as long as they
               are in the following shape ``mini_batch_size, height, width, channels``
        verbose: similar to the rest of the toolbox.
        num_neurons: number of neurons in the layer
        input_shape: ``(mini_batch_size, input_size)``
        batch_norm: If provided will be used, default is ``False``.
        rng: typically ``numpy.random``.
        borrow: ``theano`` borrow, typicall ``True``.
        dropout_rate: ``0.5`` is the default.

    Notes:
        Use ``dropout_rotate_layer.output`` and ``dropout_rotate_layer.output_shape`` from
        this class. ``L1`` and ``L2`` are also public and can also can be used for regularization.
        The class also has in public ``w``, ``b`` and ``alpha``
        which are also a list in ``params``, another property of this class.
    """
    def __init__ (self,
                  input,
                  input_shape,
                  id,
                  rng = None,
                  dropout_rate = 0.5,
                  angle = None,
                  borrow = True,
                  verbose = 2):

        if verbose >= 3:
            print "... set up the dropout rotate layer"
        import pdb
        pdb.set_trace()
        if rng is None:
            rng = numpy.random
        super(dropout_rotate_layer, self).__init__ (
                                        input = input,
                                        input_shape = input_shape,
                                        id = id,
                                        borrow = borrow,
                                        verbose = verbose
                                        )
        if not dropout_rate == 0:
            self.output = _dropout(rng = rng,
                                params = self.output,
                                dropout_rate = dropout_rate)
        self.dropout_rate = dropout_rate
        if verbose >=3:
            print "... Dropped out"

if __name__ == '__main__':
    pass  <|endoftext|>


<commit_before>"""ArcI Preprocessor."""
import os
import errno

import typing
import logging
from tqdm import tqdm

from matchzoo import engine
from matchzoo import preprocessor
from matchzoo import datapack
from matchzoo.embedding import Embedding

logger = logging.getLogger(__name__)

class ArcIPreprocessor(engine.BasePreprocessor, preprocessor.SegmentMixin):
    """
    ArcI preprocessor helper.

    TODO: NEED REFACTORING.

    Example:
        >>> train_inputs = [
        ...     ("id0", "id1", "beijing", "Beijing is capital of China", 1),
        ...     ("id0", "id2", "beijing", "China is in east Asia", 0),
        ...     ("id0", "id3", "beijing", "Summer in Beijing is hot.", 1)
        ... ]
        >>> arci_preprocessor = ArcIPreprocessor()
        >>> rv_train = arci_preprocessor.fit_transform(
        ...     train_inputs,
        ...     stage='train')
        >>> type(rv_train)
        <class 'matchzoo.datapack.DataPack'>
        >>> test_inputs = [("id0",
        ...                 "id4",
        ...                 "beijing",
        ...                 "I visted beijing yesterday.")]
        >>> rv_test = arci_preprocessor.fit_transform(
        ...     test_inputs,
        ...     stage='test')
        >>> type(rv_test)
        <class 'matchzoo.datapack.DataPack'>

    """

    def __init__(self, embedding_file: str=''):
        """Initialization."""
        self._datapack = None
        self._cache_left = []
        self._cache_right = []
        self._context = {}
        self._embedding_file = embedding_file
        self._vocab_unit = preprocessor.VocabularyUnit()

    def _prepare_stateless_units(self) -> list:
        """Prepare needed process units."""
        return [
            preprocessor.TokenizeUnit(),
            preprocessor.LowercaseUnit(),
            preprocessor.PuncRemovalUnit(),
            preprocessor.StopRemovalUnit()
        ]

    def fit(self, inputs: typing.List[tuple]):
        """
        Fit pre-processing context for transformation.

        :param inputs: Inputs to be preprocessed.
        :return: class:`ArcIPreprocessor` instance.
        """
        vocab = []
        units = self._prepare_stateless_units()

        logger.info("Start building vocabulary & fitting parameters.")

        # Convert user input into a datapack object.
        self._datapack = self.segment(inputs, stage='train')

        # Loop through user input to generate words.
        # 1. Used for build vocabulary of words (get dimension).
        # 2. Cached words can be further used to perform input
        #    transformation.
        left = self._datapack.left
        right = self._datapack.right

        for idx, row in tqdm(left.iterrows()):
            # For each piece of text, apply process unit sequentially.
            text = row.text_left
            for unit in units:
                text = unit.transform(text)
            vocab.extend(text)
            # cache words for transformation.
            self._cache_left.append((row.name, text))

        for idx, row in tqdm(right.iterrows()):
            # For each piece of text, apply process unit sequentially.
            text = row.text_right
            for unit in units:
                text = unit.transform(text)
            vocab.extend(text)
            # cache words for transformation.
            self._cache_right.append((row.name, text))

        # Initialize a vocabulary process unit to build words vocab.
        self._vocab_unit.fit(vocab)

        if len(self._embedding_file) == 0:
            pass
        elif os.path.isfile(self._embedding_file):
            embed_module = Embedding(embedding_file=self._embedding_file)
            embed_module.build(self._vocab_unit.state['term_index'])
            self._context['embedding_mat'] = embed_module.embedding_mat
        else:
            logger.error("Embedding file [{}] not found."
                         .format(self._embedding_file))
            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),
                                    self._embedding_file)

        # Store the fitted parameters in context.
        self._context['term_index'] = self._vocab_unit.state['term_index']
        self._datapack.context = self._context
        return self

    def transform(
        self,
        inputs: typing.List[tuple],
        stage: str
    ) -> datapack.DataPack:
        """
        Apply transformation on data, create word ids.

        :param inputs: Inputs to be preprocessed.
        :param stage: Pre-processing stage, `train` or `test`.

        :return: Transformed data as :class:`DataPack` object.
        """
        if stage not in ['train', 'test']:
            raise ValueError(f'{stage} is not a valid stage name.')
        if not self._context.get('term_index'):
            raise ValueError(
                "Please fit term_index before apply transofm function.")

        logger.info(f"Start processing input data for {stage} stage.")

        if stage == 'train':
            # use cached data directly.
            for idx, word in tqdm(self._cache_left):
                word = self._vocab_unit.transform(word)
                self._datapack.left.at[idx, 'text_left'] = word
            for idx, word in tqdm(self._cache_right):
                word = self._vocab_unit.transform(word)
                self._datapack.right.at[idx, 'text_right'] = word
            return self._datapack
        else:
            # do preprocessing from scrach.
            units = self._prepare_stateless_units()
            units.append(self._vocab_unit)
            self._datapack = self.segment(inputs, stage='test')

            left = self._datapack.left
            right = self._datapack.right

            for idx, row in tqdm(left.iterrows()):
                text = row.text_left
                for unit in units:
                    text = unit.transform(text)
                self._datapack.left.at[idx, 'text_left'] = text
            for idx, row in tqdm(right.iterrows()):
                text = row.text_right
                for unit in units:
                    text = unit.transform(text)
                self._datapack.right.at[idx, 'text_right'] = text

            return self._datapack
<commit_msg>[Feature] Add ArcI Preprocessor<commit_after>"""ArcI Preprocessor."""
import os
import errno

import typing
import logging
from tqdm import tqdm

from matchzoo import engine
from matchzoo import preprocessor
from matchzoo import datapack
from matchzoo.embedding import Embedding

logger = logging.getLogger(__name__)

class ArcIPreprocessor(engine.BasePreprocessor, preprocessor.SegmentMixin):
    """
    ArcI preprocessor helper.

    TODO: NEED REFACTORING.

    Example:
        >>> train_inputs = [
        ...     ("id0", "id1", "beijing", "Beijing is capital of China", 1),
        ...     ("id0", "id2", "beijing", "China is in east Asia", 0),
        ...     ("id0", "id3", "beijing", "Summer in Beijing is hot.", 1)
        ... ]
        >>> arci_preprocessor = ArcIPreprocessor()
        >>> rv_train = arci_preprocessor.fit_transform(
        ...     train_inputs,
        ...     stage='train')
        >>> type(rv_train)
        <class 'matchzoo.datapack.DataPack'>
        >>> test_inputs = [("id0",
        ...                 "id4",
        ...                 "beijing",
        ...                 "I visted beijing yesterday.")]
        >>> rv_test = arci_preprocessor.fit_transform(
        ...     test_inputs,
        ...     stage='test')
        >>> type(rv_test)
        <class 'matchzoo.datapack.DataPack'>

    """

    def __init__(self, embedding_file: str=''):
        """Initialization."""
        self._datapack = None
        self._context = {}
        self._embedding_file = embedding_file
        self._vocab_unit = preprocessor.VocabularyUnit()

    def _prepare_stateless_units(self) -> list:
        """Prepare needed process units."""
        return [
            preprocessor.TokenizeUnit(),
            preprocessor.LowercaseUnit(),
            preprocessor.PuncRemovalUnit(),
            preprocessor.StopRemovalUnit()
        ]

    def fit(self, inputs: typing.List[tuple]):
        """
        Fit pre-processing context for transformation.

        :param inputs: Inputs to be preprocessed.
        :return: class:`ArcIPreprocessor` instance.
        """
        vocab = []
        units = self._prepare_stateless_units()

        logger.info("Start building vocabulary & fitting parameters.")

        # Convert user input into a datapack object.
        self._datapack = self.segment(inputs, stage='train')

        # Loop through user input to generate words.
        # 1. Used for build vocabulary of words (get dimension).
        # 2. Cached words can be further used to perform input
        #    transformation.
        left = self._datapack.left
        right = self._datapack.right

        for idx, row in tqdm(left.iterrows()):
            # For each piece of text, apply process unit sequentially.
            text = row.text_left
            for unit in units:
                text = unit.transform(text)
            vocab.extend(text)

        for idx, row in tqdm(right.iterrows()):
            # For each piece of text, apply process unit sequentially.
            text = row.text_right
            for unit in units:
                text = unit.transform(text)
            vocab.extend(text)

        # Initialize a vocabulary process unit to build words vocab.
        self._vocab_unit.fit(vocab)

        if len(self._embedding_file) == 0:
            pass
        elif os.path.isfile(self._embedding_file):
            embed_module = Embedding(embedding_file=self._embedding_file)
            embed_module.build(self._vocab_unit.state['term_index'])
            self._context['embedding_mat'] = embed_module.embedding_mat
        else:
            logger.error("Embedding file [{}] not found."
                         .format(self._embedding_file))
            raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT),
                                    self._embedding_file)

        # Store the fitted parameters in context.
        self._context['term_index'] = self._vocab_unit.state['term_index']
        self._datapack.context = self._context
        return self

    def transform(
        self,
        inputs: typing.List[tuple],
        stage: str
    ) -> datapack.DataPack:
        """
        Apply transformation on data, create word ids.

        :param inputs: Inputs to be preprocessed.
        :param stage: Pre-processing stage, `train` or `test`.

        :return: Transformed data as :class:`DataPack` object.
        """
        if stage not in ['train', 'test']:
            raise ValueError(f'{stage} is not a valid stage name.')
        if not self._context.get('term_index'):
            raise ValueError(
                "Please fit term_index before apply transofm function.")

        logger.info(f"Start processing input data for {stage} stage.")

        # do preprocessing from scrach.
        units = self._prepare_stateless_units()
        units.append(self._vocab_unit)
        self._datapack = self.segment(inputs, stage=stage)

        left = self._datapack.left
        right = self._datapack.right

        for idx, row in tqdm(left.iterrows()):
            text = row.text_left
            for unit in units:
                text = unit.transform(text)
            self._datapack.left.at[idx, 'text_left'] = text
        for idx, row in tqdm(right.iterrows()):
            text = row.text_right
            for unit in units:
                text = unit.transform(text)
            self._datapack.right.at[idx, 'text_right'] = text

        return self._datapack
<|endoftext|>


<commit_before>from collections import defaultdict, OrderedDict
import os
import sys
import warnings

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache
from django.utils.module_loading import import_lock
from django.utils._os import upath

from .base import AppConfig

class Apps(object):
    """
    A registry that stores the configuration of installed applications.

    It also keeps track of models eg. to provide reverse-relations.
    """

    def __init__(self, master=False):
        # Only one master registry may exist at a given time, and it shall be
        # the apps variable defined at the end of this module.
        if master and hasattr(sys.modules[__name__], 'apps'):
            raise RuntimeError("You may create only one master registry.")

        # Mapping of app labels => model names => model classes. Every time a
        # model is imported, ModelBase.__new__ calls apps.register_model which
        # creates an entry in all_models. All imported models are registered,
        # regardless of whether they're defined in an installed application
        # and whether the registry has been populated. Since it isn't possible
        # to reimport a module safely (it could reexecute initialization code)
        # all_models is never overridden or reset.
        self.all_models = defaultdict(OrderedDict)

        # Mapping of labels to AppConfig instances for installed apps.
        self.app_configs = OrderedDict()

        # Stack of app_configs. Used to store the current state in
        # set_available_apps and set_installed_apps.
        self.stored_app_configs = []

        # Internal flags used when populating the registry.
        self._apps_loaded = False
        self._models_loaded = False

        # Pending lookups for lazy relations.
        self._pending_lookups = {}

    def populate_apps(self, installed_apps=None):
        """
        Populate app-related information.

        This method imports each application module.

        It is thread safe and idempotent, but not reentrant.
        """
        if self._apps_loaded:
            return
        # Since populate_apps() may be a side effect of imports, and since
        # it will itself import modules, an ABBA deadlock between threads
        # would be possible if we didn't take the import lock. See #18251.
        with import_lock():
            if self._apps_loaded:
                return

            # app_config should be pristine, otherwise the code below won't
            # guarantee that the order matches the order in INSTALLED_APPS.
            if self.app_configs:
                raise RuntimeError("populate_apps() isn't reentrant")

            # Application modules aren't expected to import anything, and
            # especially not other application modules, even indirectly.
            # Therefore we simply import them sequentially.
            if installed_apps is None:
                installed_apps = settings.INSTALLED_APPS
            for entry in installed_apps:
                if isinstance(entry, AppConfig):
                    app_config = entry
                else:
                    app_config = AppConfig.create(entry)
                self.app_configs[app_config.label] = app_config

            self.clear_cache()
            self._apps_loaded = True

    def populate_models(self):
        """
        Populate model-related information.

        This method imports each models module.

        It is thread safe, idempotent and reentrant.
        """
        if self._models_loaded:
            return
        # Since populate_models() may be a side effect of imports, and since
        # it will itself import modules, an ABBA deadlock between threads
        # would be possible if we didn't take the import lock. See #18251.
        with import_lock():
            if self._models_loaded:
                return

            self.populate_apps()

            # Models modules are likely to import other models modules, for
            # example to reference related objects. As a consequence:
            # - we deal with import loops by postponing affected modules.
            # - we provide reentrancy by making import_models() idempotent.

            outermost = not hasattr(self, '_postponed')
            if outermost:
                self._postponed = []

            for app_config in self.app_configs.values():

                if app_config.models is not None:
                    continue

                try:
                    all_models = self.all_models[app_config.label]
                    app_config.import_models(all_models)
                except ImportError:
                    self._postponed.append(app_config)

            if outermost:
                for app_config in self._postponed:
                    all_models = self.all_models[app_config.label]
                    app_config.import_models(all_models)

                del self._postponed

                self.clear_cache()
                self._models_loaded = True

    @property
    def ready(self):
        """
        Whether the registry is fully populated.

        Useful for code that wants to cache the results of get_models() for
        themselves once it is safe to do so.
        """
        return self._models_loaded              # implies self._apps_loaded.

    def get_app_configs(self, only_with_models_module=False):
        """
        Imports applications and returns an iterable of app configs.

        If only_with_models_module in True (non-default), imports models and
        considers only applications containing a models module.
        """
        if only_with_models_module:
            self.populate_models()
        else:
            self.populate_apps()

        for app_config in self.app_configs.values():
            if only_with_models_module and app_config.models_module is None:
                continue
            yield app_config

    def get_app_config(self, app_label, only_with_models_module=False):
        """
        Imports applications and returns an app config for the given label.

        Raises LookupError if no application exists with this label.

        If only_with_models_module in True (non-default), imports models and
        considers only applications containing a models module.
        """
        if only_with_models_module:
            self.populate_models()
        else:
            self.populate_apps()

        app_config = self.app_configs.get(app_label)
        if app_config is None:
            raise LookupError("No installed app with label '%s'." % app_label)
        if only_with_models_module and app_config.models_module is None:
            raise LookupError("App '%s' doesn't have a models module." % app_label)
        return app_config

    # This method is performance-critical at least for Django's test suite.
    @lru_cache.lru_cache(maxsize=None)
    def get_models(self, app_mod=None, include_auto_created=False,
                   include_deferred=False, include_swapped=False):
        """
        Given a module containing models, returns a list of the models.
        Otherwise returns a list of all installed models.

        By default, auto-created models (i.e., m2m models without an
        explicit intermediate table) are not included. However, if you
        specify include_auto_created=True, they will be.

        By default, models created to satisfy deferred attribute
        queries are *not* included in the list of models. However, if
        you specify include_deferred, they will be.

        By default, models that have been swapped out will *not* be
        included in the list of models. However, if you specify
        include_swapped, they will be.
        """
        model_list = None
        self.populate_models()
        if app_mod:
            app_label = app_mod.__name__.split('.')[-2]
            try:
                model_dicts = [self.app_configs[app_label].models]
            except KeyError:
                model_dicts = []
        else:
            model_dicts = [app_config.models for app_config in self.app_configs.values()]
        model_list = []
        for model_dict in model_dicts:
            model_list.extend(
                model for model in model_dict.values()
                if ((not model._deferred or include_deferred) and
                    (not model._meta.auto_created or include_auto_created) and
                    (not model._meta.swapped or include_swapped))
            )
        return model_list

    def get_model(self, app_label, model_name):
        """
        Returns the model matching the given app_label and model_name.

        model_name is case-insensitive.

        Raises LookupError if no application exists with this label, or no
        model exists with this name in the application.
        """
        self.populate_models()
        return self.get_app_config(app_label).get_model(model_name.lower())

    def register_model(self, app_label, model):
        # Since this method is called when models are imported, it cannot
        # perform imports because of the risk of import loops. It mustn't
        # call get_app_config().
        model_name = model._meta.model_name
        app_models = self.all_models[app_label]
        # Defensive check for extra safety.
        if model_name in app_models:
            raise RuntimeError(
                "Conflicting '%s' models in application '%s': %s and %s." %
                (model_name, app_label, app_models[model_name], model))
        app_models[model_name] = model
        self.clear_cache()

    def has_app(self, app_name):
        """
        Checks whether an application with this name exists in the registry.

        app_name is the full name of the app eg. 'django.contrib.admin'.

        It's safe to call this method at import time, even while the registry
        is being populated. It returns False for apps that aren't loaded yet.
        """
        app_config = self.app_configs.get(app_name.rpartition(".")[2])
        return app_config is not None and app_config.name == app_name

    def get_registered_model(self, app_label, model_name):
        """
        Similar to get_model(), but doesn't require that an app exists with
        the given app_label.

        It's safe to call this method at import time, even while the registry
        is being populated.
        """
        model = self.all_models[app_label].get(model_name.lower())
        if model is None:
            raise LookupError(
                "Model '%s.%s' not registered." % (app_label, model_name))
        return model

    def set_available_apps(self, available):
        """
        Restricts the set of installed apps used by get_app_config[s].

        available must be an iterable of application names.

        set_available_apps() must be balanced with unset_available_apps().

        Primarily used for performance optimization in TransactionTestCase.

        This method is safe is the sense that it doesn't trigger any imports.
        """
        available = set(available)
        installed = set(app_config.name for app_config in self.get_app_configs())
        if not available.issubset(installed):
            raise ValueError("Available apps isn't a subset of installed "
                "apps, extra apps: %s" % ", ".join(available - installed))

        self.stored_app_configs.append(self.app_configs)
        self.app_configs = OrderedDict(
            (label, app_config)
            for label, app_config in self.app_configs.items()
            if app_config.name in available)
        self.clear_cache()

    def unset_available_apps(self):
        """
        Cancels a previous call to set_available_apps().
        """
        self.app_configs = self.stored_app_configs.pop()
        self.clear_cache()

    def set_installed_apps(self, installed):
        """
        Enables a different set of installed apps for get_app_config[s].

        installed must be an iterable in the same format as INSTALLED_APPS.

        set_installed_apps() must be balanced with unset_installed_apps(),
        even if it exits with an exception.

        Primarily used as a receiver of the setting_changed signal in tests.

        This method may trigger new imports, which may add new models to the
        registry of all imported models. They will stay in the registry even
        after unset_installed_apps(). Since it isn't possible to replay
        imports safely (eg. that could lead to registering listeners twice),
        models are registered when they're imported and never removed.
        """
        self.stored_app_configs.append((self.app_configs, self._apps_loaded, self._models_loaded))
        self.app_configs = OrderedDict()
        self.clear_cache()
        self._apps_loaded = False
        self.populate_apps(installed)
        self._models_loaded = False
        self.populate_models()

    def unset_installed_apps(self):
        """
        Cancels a previous call to set_installed_apps().
        """
        self.app_configs, self._apps_loaded, self._models_loaded = self.stored_app_configs.pop()
        self.clear_cache()

    def clear_cache(self):
        """
        Clears all internal caches, for methods that alter the app registry.

        This is mostly used in tests.
        """
        self.clear_cache()

    ### DEPRECATED METHODS GO BELOW THIS LINE ###

    def load_app(self, app_name):
        """
        Loads the app with the provided fully qualified name, and returns the
        model module.
        """
        warnings.warn(
            "load_app(app_name) is deprecated.",
            PendingDeprecationWarning, stacklevel=2)
        app_config = AppConfig.create(app_name)
        app_config.import_models(self.all_models[app_config.label])
        self.app_configs[app_config.label] = app_config
        self.clear_cache()
        return app_config.models_module

    def app_cache_ready(self):
        warnings.warn(
            "app_cache_ready() is deprecated in favor of the ready property.",
            PendingDeprecationWarning, stacklevel=2)
        return self.ready

    def get_app(self, app_label):
        """
        Returns the module containing the models for the given app_label.
        """
        warnings.warn(
            "get_app_config(app_label).models_module supersedes get_app(app_label).",
            PendingDeprecationWarning, stacklevel=2)
        try:
            return self.get_app_config(
                app_label, only_with_models_module=True).models_module
        except LookupError as exc:
            # Change the exception type for backwards compatibility.
            raise ImproperlyConfigured(*exc.args)

    def get_apps(self):
        """
        Returns a list of all installed modules that contain models.
        """
        warnings.warn(
            "[a.models_module for a in get_app_configs()] supersedes get_apps().",
            PendingDeprecationWarning, stacklevel=2)
        app_configs = self.get_app_configs(only_with_models_module=True)
        return [app_config.models_module for app_config in app_configs]

    def _get_app_package(self, app):
        return '.'.join(app.__name__.split('.')[:-1])

    def get_app_package(self, app_label):
        warnings.warn(
            "get_app_config(label).name supersedes get_app_package(label).",
            PendingDeprecationWarning, stacklevel=2)
        return self._get_app_package(self.get_app(app_label))

    def _get_app_path(self, app):
        if hasattr(app, '__path__'):        # models/__init__.py package
            app_path = app.__path__[0]
        else:                               # models.py module
            app_path = app.__file__
        return os.path.dirname(upath(app_path))

    def get_app_path(self, app_label):
        warnings.warn(
            "get_app_config(label).path supersedes get_app_path(label).",
            PendingDeprecationWarning, stacklevel=2)
        return self._get_app_path(self.get_app(app_label))

    def get_app_paths(self):
        """
        Returns a list of paths to all installed apps.

        Useful for discovering files at conventional locations inside apps
        (static files, templates, etc.)
        """
        warnings.warn(
            "[a.path for a in get_app_configs()] supersedes get_app_paths().",
            PendingDeprecationWarning, stacklevel=2)

        self.populate_models()

        app_paths = []
        for app in self.get_apps():
            app_paths.append(self._get_app_path(app))
        return app_paths

    def register_models(self, app_label, *models):
        """
        Register a set of models as belonging to an app.
        """
        warnings.warn(
            "register_models(app_label, *models) is deprecated.",
            PendingDeprecationWarning, stacklevel=2)
        for model in models:
            self.register_model(app_label, model)

apps = Apps(master=True)
<commit_msg>Fixed stupid error in 21f22f95.<commit_after>from collections import defaultdict, OrderedDict
import os
import sys
import warnings

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils import lru_cache
from django.utils.module_loading import import_lock
from django.utils._os import upath

from .base import AppConfig

class Apps(object):
    """
    A registry that stores the configuration of installed applications.

    It also keeps track of models eg. to provide reverse-relations.
    """

    def __init__(self, master=False):
        # Only one master registry may exist at a given time, and it shall be
        # the apps variable defined at the end of this module.
        if master and hasattr(sys.modules[__name__], 'apps'):
            raise RuntimeError("You may create only one master registry.")

        # Mapping of app labels => model names => model classes. Every time a
        # model is imported, ModelBase.__new__ calls apps.register_model which
        # creates an entry in all_models. All imported models are registered,
        # regardless of whether they're defined in an installed application
        # and whether the registry has been populated. Since it isn't possible
        # to reimport a module safely (it could reexecute initialization code)
        # all_models is never overridden or reset.
        self.all_models = defaultdict(OrderedDict)

        # Mapping of labels to AppConfig instances for installed apps.
        self.app_configs = OrderedDict()

        # Stack of app_configs. Used to store the current state in
        # set_available_apps and set_installed_apps.
        self.stored_app_configs = []

        # Internal flags used when populating the registry.
        self._apps_loaded = False
        self._models_loaded = False

        # Pending lookups for lazy relations.
        self._pending_lookups = {}

    def populate_apps(self, installed_apps=None):
        """
        Populate app-related information.

        This method imports each application module.

        It is thread safe and idempotent, but not reentrant.
        """
        if self._apps_loaded:
            return
        # Since populate_apps() may be a side effect of imports, and since
        # it will itself import modules, an ABBA deadlock between threads
        # would be possible if we didn't take the import lock. See #18251.
        with import_lock():
            if self._apps_loaded:
                return

            # app_config should be pristine, otherwise the code below won't
            # guarantee that the order matches the order in INSTALLED_APPS.
            if self.app_configs:
                raise RuntimeError("populate_apps() isn't reentrant")

            # Application modules aren't expected to import anything, and
            # especially not other application modules, even indirectly.
            # Therefore we simply import them sequentially.
            if installed_apps is None:
                installed_apps = settings.INSTALLED_APPS
            for entry in installed_apps:
                if isinstance(entry, AppConfig):
                    app_config = entry
                else:
                    app_config = AppConfig.create(entry)
                self.app_configs[app_config.label] = app_config

            self.clear_cache()
            self._apps_loaded = True

    def populate_models(self):
        """
        Populate model-related information.

        This method imports each models module.

        It is thread safe, idempotent and reentrant.
        """
        if self._models_loaded:
            return
        # Since populate_models() may be a side effect of imports, and since
        # it will itself import modules, an ABBA deadlock between threads
        # would be possible if we didn't take the import lock. See #18251.
        with import_lock():
            if self._models_loaded:
                return

            self.populate_apps()

            # Models modules are likely to import other models modules, for
            # example to reference related objects. As a consequence:
            # - we deal with import loops by postponing affected modules.
            # - we provide reentrancy by making import_models() idempotent.

            outermost = not hasattr(self, '_postponed')
            if outermost:
                self._postponed = []

            for app_config in self.app_configs.values():

                if app_config.models is not None:
                    continue

                try:
                    all_models = self.all_models[app_config.label]
                    app_config.import_models(all_models)
                except ImportError:
                    self._postponed.append(app_config)

            if outermost:
                for app_config in self._postponed:
                    all_models = self.all_models[app_config.label]
                    app_config.import_models(all_models)

                del self._postponed

                self.clear_cache()
                self._models_loaded = True

    @property
    def ready(self):
        """
        Whether the registry is fully populated.

        Useful for code that wants to cache the results of get_models() for
        themselves once it is safe to do so.
        """
        return self._models_loaded              # implies self._apps_loaded.

    def get_app_configs(self, only_with_models_module=False):
        """
        Imports applications and returns an iterable of app configs.

        If only_with_models_module in True (non-default), imports models and
        considers only applications containing a models module.
        """
        if only_with_models_module:
            self.populate_models()
        else:
            self.populate_apps()

        for app_config in self.app_configs.values():
            if only_with_models_module and app_config.models_module is None:
                continue
            yield app_config

    def get_app_config(self, app_label, only_with_models_module=False):
        """
        Imports applications and returns an app config for the given label.

        Raises LookupError if no application exists with this label.

        If only_with_models_module in True (non-default), imports models and
        considers only applications containing a models module.
        """
        if only_with_models_module:
            self.populate_models()
        else:
            self.populate_apps()

        app_config = self.app_configs.get(app_label)
        if app_config is None:
            raise LookupError("No installed app with label '%s'." % app_label)
        if only_with_models_module and app_config.models_module is None:
            raise LookupError("App '%s' doesn't have a models module." % app_label)
        return app_config

    # This method is performance-critical at least for Django's test suite.
    @lru_cache.lru_cache(maxsize=None)
    def get_models(self, app_mod=None, include_auto_created=False,
                   include_deferred=False, include_swapped=False):
        """
        Given a module containing models, returns a list of the models.
        Otherwise returns a list of all installed models.

        By default, auto-created models (i.e., m2m models without an
        explicit intermediate table) are not included. However, if you
        specify include_auto_created=True, they will be.

        By default, models created to satisfy deferred attribute
        queries are *not* included in the list of models. However, if
        you specify include_deferred, they will be.

        By default, models that have been swapped out will *not* be
        included in the list of models. However, if you specify
        include_swapped, they will be.
        """
        model_list = None
        self.populate_models()
        if app_mod:
            app_label = app_mod.__name__.split('.')[-2]
            try:
                model_dicts = [self.app_configs[app_label].models]
            except KeyError:
                model_dicts = []
        else:
            model_dicts = [app_config.models for app_config in self.app_configs.values()]
        model_list = []
        for model_dict in model_dicts:
            model_list.extend(
                model for model in model_dict.values()
                if ((not model._deferred or include_deferred) and
                    (not model._meta.auto_created or include_auto_created) and
                    (not model._meta.swapped or include_swapped))
            )
        return model_list

    def get_model(self, app_label, model_name):
        """
        Returns the model matching the given app_label and model_name.

        model_name is case-insensitive.

        Raises LookupError if no application exists with this label, or no
        model exists with this name in the application.
        """
        self.populate_models()
        return self.get_app_config(app_label).get_model(model_name.lower())

    def register_model(self, app_label, model):
        # Since this method is called when models are imported, it cannot
        # perform imports because of the risk of import loops. It mustn't
        # call get_app_config().
        model_name = model._meta.model_name
        app_models = self.all_models[app_label]
        # Defensive check for extra safety.
        if model_name in app_models:
            raise RuntimeError(
                "Conflicting '%s' models in application '%s': %s and %s." %
                (model_name, app_label, app_models[model_name], model))
        app_models[model_name] = model
        self.clear_cache()

    def has_app(self, app_name):
        """
        Checks whether an application with this name exists in the registry.

        app_name is the full name of the app eg. 'django.contrib.admin'.

        It's safe to call this method at import time, even while the registry
        is being populated. It returns False for apps that aren't loaded yet.
        """
        app_config = self.app_configs.get(app_name.rpartition(".")[2])
        return app_config is not None and app_config.name == app_name

    def get_registered_model(self, app_label, model_name):
        """
        Similar to get_model(), but doesn't require that an app exists with
        the given app_label.

        It's safe to call this method at import time, even while the registry
        is being populated.
        """
        model = self.all_models[app_label].get(model_name.lower())
        if model is None:
            raise LookupError(
                "Model '%s.%s' not registered." % (app_label, model_name))
        return model

    def set_available_apps(self, available):
        """
        Restricts the set of installed apps used by get_app_config[s].

        available must be an iterable of application names.

        set_available_apps() must be balanced with unset_available_apps().

        Primarily used for performance optimization in TransactionTestCase.

        This method is safe is the sense that it doesn't trigger any imports.
        """
        available = set(available)
        installed = set(app_config.name for app_config in self.get_app_configs())
        if not available.issubset(installed):
            raise ValueError("Available apps isn't a subset of installed "
                "apps, extra apps: %s" % ", ".join(available - installed))

        self.stored_app_configs.append(self.app_configs)
        self.app_configs = OrderedDict(
            (label, app_config)
            for label, app_config in self.app_configs.items()
            if app_config.name in available)
        self.clear_cache()

    def unset_available_apps(self):
        """
        Cancels a previous call to set_available_apps().
        """
        self.app_configs = self.stored_app_configs.pop()
        self.clear_cache()

    def set_installed_apps(self, installed):
        """
        Enables a different set of installed apps for get_app_config[s].

        installed must be an iterable in the same format as INSTALLED_APPS.

        set_installed_apps() must be balanced with unset_installed_apps(),
        even if it exits with an exception.

        Primarily used as a receiver of the setting_changed signal in tests.

        This method may trigger new imports, which may add new models to the
        registry of all imported models. They will stay in the registry even
        after unset_installed_apps(). Since it isn't possible to replay
        imports safely (eg. that could lead to registering listeners twice),
        models are registered when they're imported and never removed.
        """
        self.stored_app_configs.append((self.app_configs, self._apps_loaded, self._models_loaded))
        self.app_configs = OrderedDict()
        self.clear_cache()
        self._apps_loaded = False
        self.populate_apps(installed)
        self._models_loaded = False
        self.populate_models()

    def unset_installed_apps(self):
        """
        Cancels a previous call to set_installed_apps().
        """
        self.app_configs, self._apps_loaded, self._models_loaded = self.stored_app_configs.pop()
        self.clear_cache()

    def clear_cache(self):
        """
        Clears all internal caches, for methods that alter the app registry.

        This is mostly used in tests.
        """
        self.get_models.cache_clear()

    ### DEPRECATED METHODS GO BELOW THIS LINE ###

    def load_app(self, app_name):
        """
        Loads the app with the provided fully qualified name, and returns the
        model module.
        """
        warnings.warn(
            "load_app(app_name) is deprecated.",
            PendingDeprecationWarning, stacklevel=2)
        app_config = AppConfig.create(app_name)
        app_config.import_models(self.all_models[app_config.label])
        self.app_configs[app_config.label] = app_config
        self.clear_cache()
        return app_config.models_module

    def app_cache_ready(self):
        warnings.warn(
            "app_cache_ready() is deprecated in favor of the ready property.",
            PendingDeprecationWarning, stacklevel=2)
        return self.ready

    def get_app(self, app_label):
        """
        Returns the module containing the models for the given app_label.
        """
        warnings.warn(
            "get_app_config(app_label).models_module supersedes get_app(app_label).",
            PendingDeprecationWarning, stacklevel=2)
        try:
            return self.get_app_config(
                app_label, only_with_models_module=True).models_module
        except LookupError as exc:
            # Change the exception type for backwards compatibility.
            raise ImproperlyConfigured(*exc.args)

    def get_apps(self):
        """
        Returns a list of all installed modules that contain models.
        """
        warnings.warn(
            "[a.models_module for a in get_app_configs()] supersedes get_apps().",
            PendingDeprecationWarning, stacklevel=2)
        app_configs = self.get_app_configs(only_with_models_module=True)
        return [app_config.models_module for app_config in app_configs]

    def _get_app_package(self, app):
        return '.'.join(app.__name__.split('.')[:-1])

    def get_app_package(self, app_label):
        warnings.warn(
            "get_app_config(label).name supersedes get_app_package(label).",
            PendingDeprecationWarning, stacklevel=2)
        return self._get_app_package(self.get_app(app_label))

    def _get_app_path(self, app):
        if hasattr(app, '__path__'):        # models/__init__.py package
            app_path = app.__path__[0]
        else:                               # models.py module
            app_path = app.__file__
        return os.path.dirname(upath(app_path))

    def get_app_path(self, app_label):
        warnings.warn(
            "get_app_config(label).path supersedes get_app_path(label).",
            PendingDeprecationWarning, stacklevel=2)
        return self._get_app_path(self.get_app(app_label))

    def get_app_paths(self):
        """
        Returns a list of paths to all installed apps.

        Useful for discovering files at conventional locations inside apps
        (static files, templates, etc.)
        """
        warnings.warn(
            "[a.path for a in get_app_configs()] supersedes get_app_paths().",
            PendingDeprecationWarning, stacklevel=2)

        self.populate_models()

        app_paths = []
        for app in self.get_apps():
            app_paths.append(self._get_app_path(app))
        return app_paths

    def register_models(self, app_label, *models):
        """
        Register a set of models as belonging to an app.
        """
        warnings.warn(
            "register_models(app_label, *models) is deprecated.",
            PendingDeprecationWarning, stacklevel=2)
        for model in models:
            self.register_model(app_label, model)

apps = Apps(master=True)
<|endoftext|>


<commit_before>import copy
from collections import namedtuple

BuildConf = namedtuple("BuildConf", "settings options env_vars build_requires")

def get_mingw_builds(mingw_configurations, mingw_installer_reference, archs):
    builds = []
    for config in mingw_configurations:
        version, arch, exception, thread = config
        if arch not in archs:
            continue
        settings = {"arch": arch, "compiler": "gcc",
                    "compiler.version": version[0:3],
                    "compiler.threads": thread,
                    "compiler.exception": exception}
        options, build_requires = _add_mingw_build_require(settings, mingw_installer_reference)

        settings.update({"compiler.libcxx": "libstdc++"})
        settings.update({"build_type": "Release"})
        builds.append(BuildConf(settings, options, {}, build_requires))
        s2 = copy.copy(settings)
        s2.update({"build_type": "Debug"})

        builds.append(BuildConf(s2, options, {}, build_requires))
    return builds

def _add_mingw_build_require(settings, mingw_installer_reference):
    installer_options = {}
    for setting in ("compiler.threads", "compiler.exception", "compiler.version", "arch"):
        setting_value = settings.get(setting, None)
        if setting_value:
            short_name = setting.split(".", 1)[-1]
            option_name = "%s:%s" % (mingw_installer_reference.name, short_name)
            installer_options[option_name] = setting_value

    return installer_options, {"*": [mingw_installer_reference]}

def get_visual_builds(visual_versions, archs, visual_runtimes, shared_option_name,
                      dll_with_static_runtime, vs10_x86_64_enabled):
    ret = []
    for visual_version in visual_versions:
        visual_version = str(visual_version)
        for arch in archs:
            if not vs10_x86_64_enabled and arch == "x86_64" and visual_version == "10":
                continue
            visual_builds = get_visual_builds_for_version(visual_runtimes, visual_version, arch,
                                                          shared_option_name, dll_with_static_runtime)

            ret.extend(visual_builds)
    return ret

def get_visual_builds_for_version(visual_runtimes, visual_version, arch, shared_option_name, dll_with_static_runtime):
    base_set = {"compiler": "Visual Studio",
                "compiler.version": visual_version,
                "arch": arch}
    sets = []

    if shared_option_name:
        if "MT" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MT"},
                         {shared_option_name: False}, {}, {}))
            if dll_with_static_runtime:
                sets.append(({"build_type": "Release", "compiler.runtime": "MT"},
                             {shared_option_name: True}, {}, {}))
        if "MTd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MTd"},
                                  {shared_option_name: False}, {}, {}))
            if dll_with_static_runtime:
                sets.append(({"build_type": "Debug", "compiler.runtime": "MTd"},
                                      {shared_option_name: True}, {}, {}))
        if "MD" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MD"},
                                  {shared_option_name: False}, {}, {}))
            sets.append(({"build_type": "Release", "compiler.runtime": "MD"},
                                  {shared_option_name: True}, {}, {}))
        if "MDd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MDd"},
                                  {shared_option_name: False}, {}, {}))
            sets.append(({"build_type": "Debug", "compiler.runtime": "MDd"},
                                  {shared_option_name: True}, {}, {}))

    else:
        if "MT" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MT"}, {}, {}, {}))
        if "MTd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MTd"}, {}, {}, {}))
        if "MDd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MDd"}, {}, {}, {}))
        if "MD" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MD"}, {}, {}, {}))

    ret = []
    for setting, options, env_vars, build_requires in sets:
        tmp = copy.copy(base_set)
        tmp.update(setting)
        ret.append(BuildConf(tmp, options, env_vars, build_requires))

    return ret

def get_build(compiler, the_arch, the_build_type, the_compiler_version, the_libcxx=None, the_shared_option_name=None, the_shared=None):
    options = {}
    if the_shared_option_name:
        options = {the_shared_option_name: the_shared}
    setts = {"arch": the_arch,
             "build_type": the_build_type,
             "compiler": compiler,
             "compiler.version": the_compiler_version}
    if the_libcxx:
        setts["compiler.libcxx"] = the_libcxx

    return BuildConf(setts, options, {}, {})

def get_osx_apple_clang_builds(apple_clang_versions, archs, shared_option_name, pure_c):
    ret = []

    # Not specified compiler or compiler version, will use the auto detected
    for compiler_version in apple_clang_versions:
        for arch in archs:
            if shared_option_name:
                for shared in [True, False]:
                    for build_type in ["Debug", "Release"]:
                        if not pure_c:
                            ret.append(get_build("apple-clang", arch, build_type, compiler_version,
                                                 "libc++", shared_option_name, shared))
                        else:
                            ret.append(get_build("apple-clang", arch, build_type, compiler_version, None, shared_option_name, shared))
            else:
                for build_type in ["Debug", "Release"]:
                    if not pure_c:
                        ret.append(get_build("apple-clang", arch, build_type, compiler_version, "libc++"))
                    else:
                        ret.append(get_build("apple-clang", arch, build_type, compiler_version))

    return ret

def get_linux_gcc_builds(gcc_versions, archs, shared_option_name, pure_c):
    ret = []
    # Not specified compiler or compiler version, will use the auto detected
    for gcc_version in gcc_versions:
        for arch in archs:
            if shared_option_name:
                for shared in [True, False]:
                    for build_type in ["Debug", "Release"]:
                        if not pure_c:
                            ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                 "libstdc++", shared_option_name, shared))
                            if float(gcc_version) > 5:
                                ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                     "libstdc++11", shared_option_name, shared))
                        else:
                            ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                 None, shared_option_name, shared))
            else:
                for build_type in ["Debug", "Release"]:
                    if not pure_c:
                        ret.append(get_build("gcc", arch, build_type, gcc_version,
                                             "libstdc++"))
                        if float(gcc_version) > 5:
                            ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                 "libstdc++11"))
                    else:
                        ret.append(get_build("gcc", arch, build_type, gcc_version))
    return ret

def get_linux_clang_builds(clang_versions, archs, shared_option_name, pure_c):
    ret = []
    # Not specified compiler or compiler version, will use the auto detected
    for clang_version in clang_versions:
        for arch in archs:
            if shared_option_name:
                for shared in [True, False]:
                    for build_type in ["Debug", "Release"]:
                        if not pure_c:
                            ret.append(get_build("clang", arch, build_type, clang_version,
                                                 "libstdc++", shared_option_name, shared))
                            ret.append(get_build("clang", arch, build_type, clang_version,
                                                 "libc++", shared_option_name, shared))
                        else:
                            ret.append(get_build("clang", arch, build_type, clang_version,
                                                 None, shared_option_name, shared))
            else:
                for build_type in ["Debug", "Release"]:
                    if not pure_c:
                        ret.append(get_build("clang", arch, build_type, clang_version,
                                             "libstdc++"))
                        ret.append(get_build("clang", arch, build_type, clang_version,
                                             "libstdc++"))
                    else:
                        ret.append(get_build("clang", arch, build_type, clang_version))
    return ret
<commit_msg>Fix default libcxx for Clang build<commit_after>import copy
from collections import namedtuple

BuildConf = namedtuple("BuildConf", "settings options env_vars build_requires")

def get_mingw_builds(mingw_configurations, mingw_installer_reference, archs):
    builds = []
    for config in mingw_configurations:
        version, arch, exception, thread = config
        if arch not in archs:
            continue
        settings = {"arch": arch, "compiler": "gcc",
                    "compiler.version": version[0:3],
                    "compiler.threads": thread,
                    "compiler.exception": exception}
        options, build_requires = _add_mingw_build_require(settings, mingw_installer_reference)

        settings.update({"compiler.libcxx": "libstdc++"})
        settings.update({"build_type": "Release"})
        builds.append(BuildConf(settings, options, {}, build_requires))
        s2 = copy.copy(settings)
        s2.update({"build_type": "Debug"})

        builds.append(BuildConf(s2, options, {}, build_requires))
    return builds

def _add_mingw_build_require(settings, mingw_installer_reference):
    installer_options = {}
    for setting in ("compiler.threads", "compiler.exception", "compiler.version", "arch"):
        setting_value = settings.get(setting, None)
        if setting_value:
            short_name = setting.split(".", 1)[-1]
            option_name = "%s:%s" % (mingw_installer_reference.name, short_name)
            installer_options[option_name] = setting_value

    return installer_options, {"*": [mingw_installer_reference]}

def get_visual_builds(visual_versions, archs, visual_runtimes, shared_option_name,
                      dll_with_static_runtime, vs10_x86_64_enabled):
    ret = []
    for visual_version in visual_versions:
        visual_version = str(visual_version)
        for arch in archs:
            if not vs10_x86_64_enabled and arch == "x86_64" and visual_version == "10":
                continue
            visual_builds = get_visual_builds_for_version(visual_runtimes, visual_version, arch,
                                                          shared_option_name, dll_with_static_runtime)

            ret.extend(visual_builds)
    return ret

def get_visual_builds_for_version(visual_runtimes, visual_version, arch, shared_option_name, dll_with_static_runtime):
    base_set = {"compiler": "Visual Studio",
                "compiler.version": visual_version,
                "arch": arch}
    sets = []

    if shared_option_name:
        if "MT" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MT"},
                         {shared_option_name: False}, {}, {}))
            if dll_with_static_runtime:
                sets.append(({"build_type": "Release", "compiler.runtime": "MT"},
                             {shared_option_name: True}, {}, {}))
        if "MTd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MTd"},
                                  {shared_option_name: False}, {}, {}))
            if dll_with_static_runtime:
                sets.append(({"build_type": "Debug", "compiler.runtime": "MTd"},
                                      {shared_option_name: True}, {}, {}))
        if "MD" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MD"},
                                  {shared_option_name: False}, {}, {}))
            sets.append(({"build_type": "Release", "compiler.runtime": "MD"},
                                  {shared_option_name: True}, {}, {}))
        if "MDd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MDd"},
                                  {shared_option_name: False}, {}, {}))
            sets.append(({"build_type": "Debug", "compiler.runtime": "MDd"},
                                  {shared_option_name: True}, {}, {}))

    else:
        if "MT" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MT"}, {}, {}, {}))
        if "MTd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MTd"}, {}, {}, {}))
        if "MDd" in visual_runtimes:
            sets.append(({"build_type": "Debug", "compiler.runtime": "MDd"}, {}, {}, {}))
        if "MD" in visual_runtimes:
            sets.append(({"build_type": "Release", "compiler.runtime": "MD"}, {}, {}, {}))

    ret = []
    for setting, options, env_vars, build_requires in sets:
        tmp = copy.copy(base_set)
        tmp.update(setting)
        ret.append(BuildConf(tmp, options, env_vars, build_requires))

    return ret

def get_build(compiler, the_arch, the_build_type, the_compiler_version, the_libcxx=None, the_shared_option_name=None, the_shared=None):
    options = {}
    if the_shared_option_name:
        options = {the_shared_option_name: the_shared}
    setts = {"arch": the_arch,
             "build_type": the_build_type,
             "compiler": compiler,
             "compiler.version": the_compiler_version}
    if the_libcxx:
        setts["compiler.libcxx"] = the_libcxx

    return BuildConf(setts, options, {}, {})

def get_osx_apple_clang_builds(apple_clang_versions, archs, shared_option_name, pure_c):
    ret = []

    # Not specified compiler or compiler version, will use the auto detected
    for compiler_version in apple_clang_versions:
        for arch in archs:
            if shared_option_name:
                for shared in [True, False]:
                    for build_type in ["Debug", "Release"]:
                        if not pure_c:
                            ret.append(get_build("apple-clang", arch, build_type, compiler_version,
                                                 "libc++", shared_option_name, shared))
                        else:
                            ret.append(get_build("apple-clang", arch, build_type, compiler_version, None, shared_option_name, shared))
            else:
                for build_type in ["Debug", "Release"]:
                    if not pure_c:
                        ret.append(get_build("apple-clang", arch, build_type, compiler_version, "libc++"))
                    else:
                        ret.append(get_build("apple-clang", arch, build_type, compiler_version))

    return ret

def get_linux_gcc_builds(gcc_versions, archs, shared_option_name, pure_c):
    ret = []
    # Not specified compiler or compiler version, will use the auto detected
    for gcc_version in gcc_versions:
        for arch in archs:
            if shared_option_name:
                for shared in [True, False]:
                    for build_type in ["Debug", "Release"]:
                        if not pure_c:
                            ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                 "libstdc++", shared_option_name, shared))
                            if float(gcc_version) > 5:
                                ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                     "libstdc++11", shared_option_name, shared))
                        else:
                            ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                 None, shared_option_name, shared))
            else:
                for build_type in ["Debug", "Release"]:
                    if not pure_c:
                        ret.append(get_build("gcc", arch, build_type, gcc_version,
                                             "libstdc++"))
                        if float(gcc_version) > 5:
                            ret.append(get_build("gcc", arch, build_type, gcc_version,
                                                 "libstdc++11"))
                    else:
                        ret.append(get_build("gcc", arch, build_type, gcc_version))
    return ret

def get_linux_clang_builds(clang_versions, archs, shared_option_name, pure_c):
    ret = []
    # Not specified compiler or compiler version, will use the auto detected
    for clang_version in clang_versions:
        for arch in archs:
            if shared_option_name:
                for shared in [True, False]:
                    for build_type in ["Debug", "Release"]:
                        if not pure_c:
                            ret.append(get_build("clang", arch, build_type, clang_version,
                                                 "libstdc++", shared_option_name, shared))
                            ret.append(get_build("clang", arch, build_type, clang_version,
                                                 "libc++", shared_option_name, shared))
                        else:
                            ret.append(get_build("clang", arch, build_type, clang_version,
                                                 None, shared_option_name, shared))
            else:
                for build_type in ["Debug", "Release"]:
                    if not pure_c:
                        ret.append(get_build("clang", arch, build_type, clang_version,
                                             "libstdc++"))
                        ret.append(get_build("clang", arch, build_type, clang_version,
                                             "libc++"))
                    else:
                        ret.append(get_build("clang", arch, build_type, clang_version))
    return ret
<|endoftext|>


<commit_before># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entry points for YAPF.

The main APIs that YAPF exposes to drive the reformatting.

  FormatFile(): reformat a file.
  FormatCode(): reformat a string of code.

These APIs have some common arguments:

  style_config: (string) Either a style name or a path to a file that contains
    formatting style settings. If None is specified, use the default style
    as set in style.DEFAULT_STYLE_FACTORY
  lines: (list of tuples of integers) A list of tuples of lines, [start, end],
    that we want to format. The lines are 1-based indexed. It can be used by
    third-party code (e.g., IDEs) when reformatting a snippet of code rather
    than a whole file.
  print_diff: (bool) Instead of returning the reformatted source, return a
    diff that turns the formatted source into reformatter source.
  verify: (bool) True if reformatted code should be verified for syntax.
"""

import difflib
import io
import logging
import re
import sys

from yapf.yapflib import blank_line_calculator
from yapf.yapflib import comment_splicer
from yapf.yapflib import continuation_splicer
from yapf.yapflib import pytree_unwrapper
from yapf.yapflib import pytree_utils
from yapf.yapflib import reformatter
from yapf.yapflib import split_penalty
from yapf.yapflib import style
from yapf.yapflib import subtype_assigner

def FormatFile(filename,
               style_config=None,
               lines=None,
               print_diff=False,
               verify=True):
  """Format a single Python file and return the formatted code.

  Arguments:
    filename: (unicode) The file to reformat.
    remaining arguments: see comment at the top of this module.

  Returns:
    The reformatted code or None if the file doesn't exist.
  """
  _CheckPythonVersion()
  original_source = _ReadFile(filename, logging.warning)
  if original_source is None:
    return None

  return FormatCode(original_source,
                    style_config=style_config,
                    filename=filename,
                    lines=lines,
                    print_diff=print_diff,
                    verify=verify)

def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=True):
  """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    remaining arguments: see comment at the top of this module.

  Returns:
    The code reformatted to conform to the desired formatting style.
  """
  _CheckPythonVersion()
  style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
  tree = pytree_utils.ParseCodeToTree(unformatted_source.rstrip() + '\n')

  # Run passes on the tree, modifying it in place.
  comment_splicer.SpliceComments(tree)
  continuation_splicer.SpliceContinuations(tree)
  subtype_assigner.AssignSubtypes(tree)
  split_penalty.ComputeSplitPenalties(tree)
  blank_line_calculator.CalculateBlankLines(tree)

  uwlines = pytree_unwrapper.UnwrapPyTree(tree)
  if not uwlines:
    return ''
  for uwl in uwlines:
    uwl.CalculateFormattingInformation()

  _MarkLinesToFormat(uwlines, lines)
  reformatted_source = reformatter.Reformat(uwlines, verify)

  if unformatted_source == reformatted_source:
    return '' if print_diff else reformatted_source

  code_diff = _GetUnifiedDiff(unformatted_source, reformatted_source,
                              filename=filename)

  if print_diff:
    return code_diff

  return reformatted_source

def _CheckPythonVersion():
  errmsg = 'yapf is only supported for Python 2.7 or 3.4+'
  if sys.version_info[0] == 2:
    if sys.version_info[1] < 7:
      raise RuntimeError(errmsg)
  elif sys.version_info[0] == 3:
    if sys.version_info[1] < 4:
      raise RuntimeError(errmsg)

def _ReadFile(filename, logger=None):
  """Read the contents of the file.

  An optional logger can be specified to emit messages to your favorite logging
  stream. If specified, then no exception is raised.

  Arguments:
    filename: (unicode) The name of the file.
    logger: (function) A function or lambda that takes a string and emits it.

  Returns:
    The contents of filename.

  Raises:
    IOError: raised during an error if a logger is not specified.
  """
  try:
    with io.open(filename, mode='r', newline='') as fd:
      source = fd.read()
    return source
  except IOError as err:
    if logger:
      logger(err)
    else:
      raise

DISABLE_PATTERN = r'^#+ +yapf: *disable$'
ENABLE_PATTERN = r'^#+ +yapf: *enable$'

def _MarkLinesToFormat(uwlines, lines):
  """Skip sections of code that we shouldn't reformat."""
  if lines:
    for uwline in uwlines:
      uwline.disable = True

    for start, end in sorted(lines):
      for uwline in uwlines:
        if uwline.lineno > end:
          break
        if uwline.lineno >= start:
          uwline.disable = False
    return

  index = 0
  while index < len(uwlines):
    uwline = uwlines[index]
    if uwline.is_comment:
      if re.search(DISABLE_PATTERN, uwline.first.value.strip(), re.IGNORECASE):
        while index < len(uwlines):
          uwline = uwlines[index]
          uwline.disable = True
          if (uwline.is_comment and
              re.search(ENABLE_PATTERN, uwline.first.value.strip(),
                        re.IGNORECASE)):
            break
          index += 1
    elif re.search(DISABLE_PATTERN, uwline.last.value.strip(), re.IGNORECASE):
      uwline.disable = True
    index += 1

def _GetUnifiedDiff(before, after, filename='code'):
  """Get a unified diff of the changes.

  Arguments:
    before: (unicode) The original source code.
    after: (unicode) The reformatted source code.
    filename: (unicode) The code's filename.

  Returns:
    The unified diff text.
  """
  before = before.splitlines()
  after = after.splitlines()
  return '\n'.join(difflib.unified_diff(before, after, filename, filename,
                                        '(original)', '(reformatted)',
                                        lineterm='')) + '\n'
<commit_msg>Expose API to external applications.<commit_after># Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Entry points for YAPF.

The main APIs that YAPF exposes to drive the reformatting.

  FormatFile(): reformat a file.
  FormatCode(): reformat a string of code.

These APIs have some common arguments:

  style_config: (string) Either a style name or a path to a file that contains
    formatting style settings. If None is specified, use the default style
    as set in style.DEFAULT_STYLE_FACTORY
  lines: (list of tuples of integers) A list of tuples of lines, [start, end],
    that we want to format. The lines are 1-based indexed. It can be used by
    third-party code (e.g., IDEs) when reformatting a snippet of code rather
    than a whole file.
  print_diff: (bool) Instead of returning the reformatted source, return a
    diff that turns the formatted source into reformatter source.
  verify: (bool) True if reformatted code should be verified for syntax.
"""

import difflib
import io
import logging
import re
import sys

from yapf.yapflib import blank_line_calculator
from yapf.yapflib import comment_splicer
from yapf.yapflib import continuation_splicer
from yapf.yapflib import pytree_unwrapper
from yapf.yapflib import pytree_utils
from yapf.yapflib import reformatter
from yapf.yapflib import split_penalty
from yapf.yapflib import style
from yapf.yapflib import subtype_assigner

def FormatFile(filename,
               style_config=None,
               lines=None,
               print_diff=False,
               verify=True):
  """Format a single Python file and return the formatted code.

  Arguments:
    filename: (unicode) The file to reformat.
    remaining arguments: see comment at the top of this module.

  Returns:
    The reformatted code or None if the file doesn't exist.
  """
  _CheckPythonVersion()
  original_source = ReadFile(filename, logging.warning)
  if original_source is None:
    return None

  return FormatCode(original_source,
                    style_config=style_config,
                    filename=filename,
                    lines=lines,
                    print_diff=print_diff,
                    verify=verify)

def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=True):
  """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    remaining arguments: see comment at the top of this module.

  Returns:
    The code reformatted to conform to the desired formatting style.
  """
  _CheckPythonVersion()
  style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
  tree = pytree_utils.ParseCodeToTree(unformatted_source.rstrip() + '\n')

  # Run passes on the tree, modifying it in place.
  comment_splicer.SpliceComments(tree)
  continuation_splicer.SpliceContinuations(tree)
  subtype_assigner.AssignSubtypes(tree)
  split_penalty.ComputeSplitPenalties(tree)
  blank_line_calculator.CalculateBlankLines(tree)

  uwlines = pytree_unwrapper.UnwrapPyTree(tree)
  if not uwlines:
    return ''
  for uwl in uwlines:
    uwl.CalculateFormattingInformation()

  _MarkLinesToFormat(uwlines, lines)
  reformatted_source = reformatter.Reformat(uwlines, verify)

  if unformatted_source == reformatted_source:
    return '' if print_diff else reformatted_source

  code_diff = _GetUnifiedDiff(unformatted_source, reformatted_source,
                              filename=filename)

  if print_diff:
    return code_diff

  return reformatted_source

def _CheckPythonVersion():
  errmsg = 'yapf is only supported for Python 2.7 or 3.4+'
  if sys.version_info[0] == 2:
    if sys.version_info[1] < 7:
      raise RuntimeError(errmsg)
  elif sys.version_info[0] == 3:
    if sys.version_info[1] < 4:
      raise RuntimeError(errmsg)

def ReadFile(filename, logger=None):
  """Read the contents of the file.

  An optional logger can be specified to emit messages to your favorite logging
  stream. If specified, then no exception is raised. This is external so that it
  can be used by third-party applications.

  Arguments:
    filename: (unicode) The name of the file.
    logger: (function) A function or lambda that takes a string and emits it.

  Returns:
    The contents of filename.

  Raises:
    IOError: raised during an error if a logger is not specified.
  """
  try:
    with io.open(filename, mode='r', newline='') as fd:
      source = fd.read()
    return source
  except IOError as err:
    if logger:
      logger(err)
    else:
      raise

DISABLE_PATTERN = r'^#+ +yapf: *disable$'
ENABLE_PATTERN = r'^#+ +yapf: *enable$'

def _MarkLinesToFormat(uwlines, lines):
  """Skip sections of code that we shouldn't reformat."""
  if lines:
    for uwline in uwlines:
      uwline.disable = True

    for start, end in sorted(lines):
      for uwline in uwlines:
        if uwline.lineno > end:
          break
        if uwline.lineno >= start:
          uwline.disable = False
    return

  index = 0
  while index < len(uwlines):
    uwline = uwlines[index]
    if uwline.is_comment:
      if re.search(DISABLE_PATTERN, uwline.first.value.strip(), re.IGNORECASE):
        while index < len(uwlines):
          uwline = uwlines[index]
          uwline.disable = True
          if (uwline.is_comment and
              re.search(ENABLE_PATTERN, uwline.first.value.strip(),
                        re.IGNORECASE)):
            break
          index += 1
    elif re.search(DISABLE_PATTERN, uwline.last.value.strip(), re.IGNORECASE):
      uwline.disable = True
    index += 1

def _GetUnifiedDiff(before, after, filename='code'):
  """Get a unified diff of the changes.

  Arguments:
    before: (unicode) The original source code.
    after: (unicode) The reformatted source code.
    filename: (unicode) The code's filename.

  Returns:
    The unified diff text.
  """
  before = before.splitlines()
  after = after.splitlines()
  return '\n'.join(difflib.unified_diff(before, after, filename, filename,
                                        '(original)', '(reformatted)',
                                        lineterm='')) + '\n'
<|endoftext|>