

from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    get_resize_output_image_size,
    normalize,
    pad,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    get_image_size,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging
from ...utils.import_utils import is_vision_available


lowerCamelCase 	=   logging.get_logger(__name__)


if is_vision_available():
       import PIL







class 		__magic_name__     (				lowerCamelCase__				):

   '''simple docstring'''




   lowerCamelCase__					:      Any        =  ['pixel_values']



   def __init__(							self,       lowercase_ = True,       lowercase_ = None,       lowercase_ = PILImageResampling.BILINEAR,       lowercase_ = True,       lowercase_ = False,       lowercase_ = True,       lowercase_ = True,       lowercase_ = 1 / 255,       lowercase_ = True,       lowercase_ = None,       lowercase_ = None,       **lowercase_,       )				->       None:






     """simple docstring"""






     super().__init__(**lowercase_			)

     a__    =size if size is not None else {'''height''': 2560, '''width''': 1920}
     if isinstance(lowercase_,       (tuple, list)			):
       # The previous feature extractor size parameter was in (width, height) format
       a__    =size[::-1]
     a__    =get_size_dict(lowercase_			)

     a__    =do_resize
     a__    =size
     a__    =resample
     a__    =do_thumbnail
     a__    =do_align_long_axis
     a__    =do_pad
     a__    =do_rescale
     a__    =rescale_factor
     a__    =do_normalize
     a__    =image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     a__    =image_std if image_std is not None else IMAGENET_STANDARD_STD



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_ = None			)				->       np.ndarray:






     """simple docstring"""






     a__, a__    =get_image_size(lowercase_			)
     a__, a__    =size['''height'''], size['''width''']

     if (output_width < output_height and input_width > input_height) or (
         output_width > output_height and input_width < input_height
     ):
       a__    =np.rotaa(lowercase_,       3			)

     if data_format is not None:
       a__    =to_channel_dimension_format(lowercase_,       lowercase_			)

     return image



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_ = False,       lowercase_ = None,       )				->       np.ndarray:






     """simple docstring"""






     a__, a__    =size['''height'''], size['''width''']
     a__, a__    =get_image_size(lowercase_			)

     a__    =output_width - input_width
     a__    =output_height - input_height

     if random_padding:
       a__    =np.random.randint(low=0,       high=delta_height + 1			)
       a__    =np.random.randint(low=0,       high=delta_width + 1			)
     else:
       a__    =delta_height // 2
       a__    =delta_width // 2

     a__    =delta_height - pad_top
     a__    =delta_width - pad_left

     a__    =((pad_top, pad_bottom), (pad_left, pad_right))
     return pad(lowercase_,       lowercase_,       data_format=lowercase_			)



   def 					_UpperCAmelCase					(							self,       *lowercase_,       **lowercase_			)				->       List[str]:






     """simple docstring"""






     logger.info('''pad is deprecated and will be removed in version 4.27. Please use pad_image instead.'''			)
     return self.pad_image(*lowercase_,       **lowercase_			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_ = PILImageResampling.BICUBIC,       lowercase_ = None,       **lowercase_,       )				->       np.ndarray:






     """simple docstring"""






     a__, a__    =get_image_size(lowercase_			)
     a__, a__    =size['''height'''], size['''width''']

     # We always resize to the smallest of either the input or output size.
     a__    =min(lowercase_,       lowercase_			)
     a__    =min(lowercase_,       lowercase_			)

     if height == input_height and width == input_width:
       return image

     if input_height > input_width:
       a__    =int(input_width * height / input_height			)
     elif input_width > input_height:
       a__    =int(input_height * width / input_width			)

     return resize(
         lowercase_,       size=(height, width),       resample=lowercase_,       reducing_gap=2.0,       data_format=lowercase_,       **lowercase_			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_ = PILImageResampling.BICUBIC,       lowercase_ = None,       **lowercase_,       )				->       np.ndarray:






     """simple docstring"""






     a__    =get_size_dict(lowercase_			)
     a__    =min(size['''height'''],       size['''width''']			)
     a__    =get_resize_output_image_size(lowercase_,       size=lowercase_,       default_to_square=lowercase_			)
     a__    =resize(lowercase_,       size=lowercase_,       resample=lowercase_,       data_format=lowercase_,       **lowercase_			)
     return resized_image



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_ = None,       **lowercase_,       )				->       List[str]:






     """simple docstring"""






     return rescale(lowercase_,       scale=lowercase_,       data_format=lowercase_,       **lowercase_			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_ = None,       **lowercase_,       )				->       np.ndarray:






     """simple docstring"""






     return normalize(lowercase_,       mean=lowercase_,       std=lowercase_,       data_format=lowercase_,       **lowercase_			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = False,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = None,       lowercase_ = ChannelDimension.FIRST,       **lowercase_,       )				->       PIL.Image.Image:






     """simple docstring"""






     a__    =do_resize if do_resize is not None else self.do_resize
     a__    =size if size is not None else self.size
     if isinstance(lowercase_,       (tuple, list)			):
       # Previous feature extractor had size in (width, height) format
       a__    =size[::-1]
     a__    =get_size_dict(lowercase_			)
     a__    =resample if resample is not None else self.resample
     a__    =do_thumbnail if do_thumbnail is not None else self.do_thumbnail
     a__    =do_align_long_axis if do_align_long_axis is not None else self.do_align_long_axis
     a__    =do_pad if do_pad is not None else self.do_pad
     a__    =do_rescale if do_rescale is not None else self.do_rescale
     a__    =rescale_factor if rescale_factor is not None else self.rescale_factor
     a__    =do_normalize if do_normalize is not None else self.do_normalize
     a__    =image_mean if image_mean is not None else self.image_mean
     a__    =image_std if image_std is not None else self.image_std

     a__    =make_list_of_images(lowercase_			)

     if not valid_images(lowercase_			):
       raise ValueError(
           '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
           '''torch.Tensor, tf.Tensor or jax.ndarray.'''			)

     if do_resize and size is None:
       raise ValueError('''Size must be specified if do_resize is True.'''			)

     if do_rescale and rescale_factor is None:
       raise ValueError('''Rescale factor must be specified if do_rescale is True.'''			)

     if do_pad and size is None:
       raise ValueError('''Size must be specified if do_pad is True.'''			)

     if do_normalize and (image_mean is None or image_std is None):
       raise ValueError('''Image mean and std must be specified if do_normalize is True.'''			)

     # All transformations expect numpy arrays.
     a__    =[to_numpy_array(lowercase_			) for image in images]

     if do_align_long_axis:
       a__    =[self.align_long_axis(lowercase_,       size=lowercase_			) for image in images]

     if do_resize:
       a__    =[self.resize(image=lowercase_,       size=lowercase_,       resample=lowercase_			) for image in images]

     if do_thumbnail:
       a__    =[self.thumbnail(image=lowercase_,       size=lowercase_			) for image in images]

     if do_pad:
       a__    =[self.pad_image(image=lowercase_,       size=lowercase_,       random_padding=lowercase_			) for image in images]

     if do_rescale:
       a__    =[self.rescale(image=lowercase_,       scale=lowercase_			) for image in images]

     if do_normalize:
       a__    =[self.normalize(image=lowercase_,       mean=lowercase_,       std=lowercase_			) for image in images]

     a__    =[to_channel_dimension_format(lowercase_,       lowercase_			) for image in images]

     a__    ={'''pixel_values''': images}
     return BatchFeature(data=lowercase_,       tensor_type=lowercase_			)



import unittest

import numpy as np

from transformers import ElectraConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
       from transformers.models.electra.modeling_flax_electra import (
           FlaxElectraForCausalLM,
           FlaxElectraForMaskedLM,
           FlaxElectraForMultipleChoice,
           FlaxElectraForPreTraining,
           FlaxElectraForQuestionAnswering,
           FlaxElectraForSequenceClassification,
           FlaxElectraForTokenClassification,
           FlaxElectraModel,
       )







class 		__magic_name__     (				unittest.TestCase				):

   '''simple docstring'''




   def __init__(							self,       lowercase_,       lowercase_=13,       lowercase_=7,       lowercase_=True,       lowercase_=True,       lowercase_=True,       lowercase_=True,       lowercase_=99,       lowercase_=24,       lowercase_=32,       lowercase_=5,       lowercase_=4,       lowercase_=37,       lowercase_="gelu",       lowercase_=0.1,       lowercase_=0.1,       lowercase_=512,       lowercase_=16,       lowercase_=2,       lowercase_=0.02,       lowercase_=4,       )				->       int:






     """simple docstring"""






     a__    =parent
     a__    =batch_size
     a__    =seq_length
     a__    =is_training
     a__    =use_attention_mask
     a__    =use_token_type_ids
     a__    =use_labels
     a__    =vocab_size
     a__    =hidden_size
     a__    =embedding_size
     a__    =num_hidden_layers
     a__    =num_attention_heads
     a__    =intermediate_size
     a__    =hidden_act
     a__    =hidden_dropout_prob
     a__    =attention_probs_dropout_prob
     a__    =max_position_embeddings
     a__    =type_vocab_size
     a__    =type_sequence_label_size
     a__    =initializer_range
     a__    =num_choices



   def 					_UpperCAmelCase					(							self			)				->       List[Any]:






     """simple docstring"""






     a__    =ids_tensor([self.batch_size, self.seq_length],       self.vocab_size			)

     a__    =None
     if self.use_attention_mask:
       a__    =random_attention_mask([self.batch_size, self.seq_length]			)

     a__    =None
     if self.use_token_type_ids:
       a__    =ids_tensor([self.batch_size, self.seq_length],       self.type_vocab_size			)

     a__    =ElectraConfig(
         vocab_size=self.vocab_size,       hidden_size=self.hidden_size,       embedding_size=self.embedding_size,       num_hidden_layers=self.num_hidden_layers,       num_attention_heads=self.num_attention_heads,       intermediate_size=self.intermediate_size,       hidden_act=self.hidden_act,       hidden_dropout_prob=self.hidden_dropout_prob,       attention_probs_dropout_prob=self.attention_probs_dropout_prob,       max_position_embeddings=self.max_position_embeddings,       type_vocab_size=self.type_vocab_size,       initializer_range=self.initializer_range,       )

     return config, input_ids, token_type_ids, attention_mask



   def 					_UpperCAmelCase					(							self			)				->       List[Any]:






     """simple docstring"""






     a__    =self.prepare_config_and_inputs()
     a__, a__, a__, a__    =config_and_inputs
     a__    ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
     return config, inputs_dict







@require_flax
class 		__magic_name__     (				lowerCamelCase__						,			unittest.TestCase				):

   '''simple docstring'''




   lowerCamelCase__					:      List[str]        =  True

   lowerCamelCase__					:      Tuple        =  (
       (
           FlaxElectraModel,
           FlaxElectraForCausalLM,
           FlaxElectraForMaskedLM,
           FlaxElectraForPreTraining,
           FlaxElectraForTokenClassification,
           FlaxElectraForQuestionAnswering,
           FlaxElectraForMultipleChoice,
           FlaxElectraForSequenceClassification,
       )
       if is_flax_available()
       else ()
   )



   def 					_UpperCAmelCase					(							self			)				->       str:






     """simple docstring"""






     a__    =FlaxElectraModelTester(self			)



   @slow
   def 					_UpperCAmelCase					(							self			)				->       str:






     """simple docstring"""






     for model_class_name in self.all_model_classes:
       if model_class_name == FlaxElectraForMaskedLM:
         a__    =model_class_name.from_pretrained('''google/electra-small-generator'''			)
       else:
         a__    =model_class_name.from_pretrained('''google/electra-small-discriminator'''			)
       a__    =model(np.ones((1, 1)			)			)
       self.assertIsNotNone(lowercase_			)
