





"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import MobileNetVaImageProcessor



class  A__       (	unittest.TestCase      ):





      def __init__(			self	,							A_	,							A_=7	,							A_=3	,							A_=18	,							A_=30	,							A_=400	,							A_=True	,							A_=None	,							A_=True	,							A_=None	,							):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       size if size is not None else {"shortest_edge": 20}
       UpperCamelCase     : Any	     =       crop_size if crop_size is not None else {"height": 18, "width": 18}
       UpperCamelCase     : List[Any]	     =       parent
       UpperCamelCase     : Tuple	     =       batch_size
       UpperCamelCase     : Union[str, Any]	     =       num_channels
       UpperCamelCase     : Union[str, Any]	     =       image_size
       UpperCamelCase     : Tuple	     =       min_resolution
       UpperCamelCase     : Union[str, Any]	     =       max_resolution
       UpperCamelCase     : List[Any]	     =       do_resize
       UpperCamelCase     : Union[str, Any]	     =       size
       UpperCamelCase     : str	     =       do_center_crop
       UpperCamelCase     : Union[str, Any]	     =       crop_size





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return {
           "do_resize": self.do_resize,
           "size": self.size,
           "do_center_crop": self.do_center_crop,
           "crop_size": self.crop_size,
       }



@require_torch
@require_vision
class  A__       (	_snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :Union[str, Any]						   =       MobileNetVaImageProcessor if is_vision_available() else None





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       MobileNetVaImageProcessingTester(self       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return self.image_processor_tester.prepare_image_processor_dict()





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       self.image_processing_class(**self.image_processor_dict       )
       self.assertTrue(hasattr(UpperCamelCase__	,							"do_resize"       )       )
       self.assertTrue(hasattr(UpperCamelCase__	,							"size"       )       )
       self.assertTrue(hasattr(UpperCamelCase__	,							"do_center_crop"       )       )
       self.assertTrue(hasattr(UpperCamelCase__	,							"crop_size"       )       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       self.image_processing_class.from_dict(self.image_processor_dict       )
       self.assertEqual(image_processor.size	,							{"shortest_edge": 20}       )
       self.assertEqual(image_processor.crop_size	,							{"height": 18, "width": 18}       )

       UpperCamelCase     : Dict	     =       self.image_processing_class.from_dict(self.image_processor_dict	,							size=42	,							crop_size=84       )
       self.assertEqual(image_processor.size	,							{"shortest_edge": 42}       )
       self.assertEqual(image_processor.crop_size	,							{"height": 84, "width": 84}       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[Any]	     =       self.image_processing_class(**self.image_processor_dict       )
       # create random PIL images
       UpperCamelCase     : int	     =       prepare_image_inputs(self.image_processor_tester	,							equal_resolution=UpperCamelCase__       )
       for image in image_inputs:
        self.assertIsInstance(UpperCamelCase__	,							Image.Image       )

       # Test not batched input
       UpperCamelCase     : List[str]	     =       image_processing(image_inputs[0]	,							return_tensors="pt"       ).pixel_values
       self.assertEqual(
           encoded_images.shape	,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,							)

       # Test batched
       UpperCamelCase     : str	     =       image_processing(UpperCamelCase__	,							return_tensors="pt"       ).pixel_values
       self.assertEqual(
           encoded_images.shape	,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,							)





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Any	     =       self.image_processing_class(**self.image_processor_dict       )
       # create random numpy tensors
       UpperCamelCase     : Any	     =       prepare_image_inputs(self.image_processor_tester	,							equal_resolution=UpperCamelCase__	,							numpify=UpperCamelCase__       )
       for image in image_inputs:
        self.assertIsInstance(UpperCamelCase__	,							np.ndarray       )

       # Test not batched input
       UpperCamelCase     : str	     =       image_processing(image_inputs[0]	,							return_tensors="pt"       ).pixel_values
       self.assertEqual(
           encoded_images.shape	,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,							)

       # Test batched
       UpperCamelCase     : Tuple	     =       image_processing(UpperCamelCase__	,							return_tensors="pt"       ).pixel_values
       self.assertEqual(
           encoded_images.shape	,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,							)





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : str	     =       self.image_processing_class(**self.image_processor_dict       )
       # create random PyTorch tensors
       UpperCamelCase     : Dict	     =       prepare_image_inputs(self.image_processor_tester	,							equal_resolution=UpperCamelCase__	,							torchify=UpperCamelCase__       )
       for image in image_inputs:
        self.assertIsInstance(UpperCamelCase__	,							torch.Tensor       )

       # Test not batched input
       UpperCamelCase     : Dict	     =       image_processing(image_inputs[0]	,							return_tensors="pt"       ).pixel_values
       self.assertEqual(
           encoded_images.shape	,							(
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,							)

       # Test batched
       UpperCamelCase     : Optional[int]	     =       image_processing(UpperCamelCase__	,							return_tensors="pt"       ).pixel_values
       self.assertEqual(
           encoded_images.shape	,							(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,							)







import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


__lowerCamelCase	:					List[str]			  =					logging.get_logger(__name__)


__lowerCamelCase	:					Any			  =					r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       raise NotImplementedError("StoppingCriteria needs to be subclassed"       )



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       max_length
       UpperCamelCase     : Dict	     =       max_position_embeddings





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       input_ids.shape[-1]
       UpperCamelCase     : str	     =       cur_len >= self.max_length
       if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
        logger.warning_once(
            "This is a friendly reminder - the current text generation call will exceed the model's predefined "
            F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
            "exceptions, performance degradation, or nothing at all."       )
       return is_done



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_       ):
       '''simple docstring'''




       warnings.warn(
           "The class `MaxNewTokensCriteria` is deprecated. "
           F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
           "with `max_length = start_length + max_new_tokens` instead."	,							A_	,							)
       UpperCamelCase     : Union[str, Any]	     =       start_length
       UpperCamelCase     : List[str]	     =       max_new_tokens
       UpperCamelCase     : Tuple	     =       start_length + max_new_tokens





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return input_ids.shape[-1] >= self.max_length



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       max_time
       UpperCamelCase     : Dict	     =       time.time() if initial_timestamp is None else initial_timestamp





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return time.time() - self.initial_timestamp > self.max_time



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return any(criteria(A_	,							A_       ) for criteria in self       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for stopping_criterium in self:
        if isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
        elif isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
       return None



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase					)						->			StoppingCriteriaList:
 UpperCamelCase     : Tuple	     =       stopping_criteria.max_length
 UpperCamelCase     : Union[str, Any]	     =       deepcopy(_lowerCAmelCase					)
 if stopping_max_length is not None and stopping_max_length != max_length:
  warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"							,       _lowerCAmelCase					)
 elif stopping_max_length is None:
  new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCAmelCase					)					)
 return new_stopping_criteria
