






'''simple docstring'''
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 (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


UpperCamelCase__			=      logging.get_logger(__name__)


if is_vision_available():
 import PIL


class 							_UpperCAmelCase    (		snake_case      ):
    __lowerCamelCase: List[str]									=     ['pixel_values']




    def __init__(      self	:							str	,  a	:							bool = True	,  a	:							Dict[str, int] = None	,  a	:							PILImageResampling = PILImageResampling.BICUBIC	,  a	:							bool = True	,  a	:							Dict[str, int] = None	,  a	:							bool = True	,  a	:							Union[int, float] = 1 / 2_5_5	,  a	:							bool = True	,  a	:							Optional[Union[float, List[float]]] = None	,  a	:							Optional[Union[float, List[float]]] = None	,  a	:							bool = True	,  **a	:							Dict	,  ):






       '''simple docstring'''






       super().__init__(**a      )
       lowercase_						:     Any							     =  size if size is not None else {"shortest_edge": 2_2_4}
       lowercase_						:     Optional[Any]							     =  get_size_dict(a	,  default_to_square=a      )
       lowercase_						:     Union[str, Any]							     =  crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
       lowercase_						:     List[str]							     =  get_size_dict(a	,  default_to_square=a	,  param_name="crop_size"      )

       lowercase_						:     int							     =  do_resize
       lowercase_						:     str							     =  size
       lowercase_						:     List[str]							     =  resample
       lowercase_						:     List[Any]							     =  do_center_crop
       lowercase_						:     Any							     =  crop_size
       lowercase_						:     Optional[Any]							     =  do_rescale
       lowercase_						:     Any							     =  rescale_factor
       lowercase_						:     int							     =  do_normalize
       lowercase_						:     Optional[int]							     =  image_mean if image_mean is not None else OPENAI_CLIP_MEAN
       lowercase_						:     Tuple							     =  image_std if image_std is not None else OPENAI_CLIP_STD
       lowercase_						:     Any							     =  do_convert_rgb




    def 					lowerCAmelCase__					(      self	:							List[str]	,  a	:							np.ndarray	,  a	:							Dict[str, int]	,  a	:							PILImageResampling = PILImageResampling.BICUBIC	,  a	:							Optional[Union[str, ChannelDimension]] = None	,  **a	:							str	,  ):






       '''simple docstring'''






       lowercase_						:     int							     =  get_size_dict(a	,  default_to_square=a      )
       if "shortest_edge" not in size:
          raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""      )
       lowercase_						:     int							     =  get_resize_output_image_size(a	,  size=size["shortest_edge"]	,  default_to_square=a      )
       return resize(a	,  size=a	,  resample=a	,  data_format=a	,  **a      )




    def 					lowerCAmelCase__					(      self	:							str	,  a	:							np.ndarray	,  a	:							Dict[str, int]	,  a	:							Optional[Union[str, ChannelDimension]] = None	,  **a	:							str	,  ):






       '''simple docstring'''






       lowercase_						:     List[str]							     =  get_size_dict(a      )
       if "height" not in size or "width" not in size:
          raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""      )
       return center_crop(a	,  size=(size["height"], size["width"])	,  data_format=a	,  **a      )




    def 					lowerCAmelCase__					(      self	:							List[str]	,  a	:							np.ndarray	,  a	:							Union[int, float]	,  a	:							Optional[Union[str, ChannelDimension]] = None	,  **a	:							List[str]	,  ):






       '''simple docstring'''






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




    def 					lowerCAmelCase__					(      self	:							str	,  a	:							np.ndarray	,  a	:							Union[float, List[float]]	,  a	:							Union[float, List[float]]	,  a	:							Optional[Union[str, ChannelDimension]] = None	,  **a	:							List[Any]	,  ):






       '''simple docstring'''






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





    def 					lowerCAmelCase__					(      self	:							List[Any]	,  a	:							ImageInput	,  a	:							bool = None	,  a	:							Dict[str, int] = None	,  a	:							PILImageResampling = None	,  a	:							bool = None	,  a	:							int = None	,  a	:							bool = None	,  a	:							float = None	,  a	:							bool = None	,  a	:							Optional[Union[float, List[float]]] = None	,  a	:							Optional[Union[float, List[float]]] = None	,  a	:							bool = None	,  a	:							Optional[Union[str, TensorType]] = None	,  a	:							Optional[ChannelDimension] = ChannelDimension.FIRST	,  **a	:							Any	,  ):






       '''simple docstring'''






       lowercase_						:     int							     =  do_resize if do_resize is not None else self.do_resize
       lowercase_						:     int							     =  size if size is not None else self.size
       lowercase_						:     Optional[int]							     =  get_size_dict(a	,  param_name="size"	,  default_to_square=a      )
       lowercase_						:     List[Any]							     =  resample if resample is not None else self.resample
       lowercase_						:     Tuple							     =  do_center_crop if do_center_crop is not None else self.do_center_crop
       lowercase_						:     int							     =  crop_size if crop_size is not None else self.crop_size
       lowercase_						:     Dict							     =  get_size_dict(a	,  param_name="crop_size"	,  default_to_square=a      )
       lowercase_						:     List[str]							     =  do_rescale if do_rescale is not None else self.do_rescale
       lowercase_						:     int							     =  rescale_factor if rescale_factor is not None else self.rescale_factor
       lowercase_						:     str							     =  do_normalize if do_normalize is not None else self.do_normalize
       lowercase_						:     Tuple							     =  image_mean if image_mean is not None else self.image_mean
       lowercase_						:     Optional[Any]							     =  image_std if image_std is not None else self.image_std
       lowercase_						:     Tuple							     =  do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

       lowercase_						:     Optional[Any]							     =  make_list_of_images(a      )

       if not valid_images(a      ):
          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_center_crop and crop_size is None:
          raise ValueError("Crop size must be specified if do_center_crop is True."      )

       if do_rescale and rescale_factor is None:
          raise ValueError("Rescale factor must be specified if do_rescale 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."      )

       # PIL RGBA images are converted to RGB
       if do_convert_rgb:
          lowercase_						:     str							     =  [convert_to_rgb(a      ) for image in images]

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

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

       if do_center_crop:
          lowercase_						:     Optional[Any]							     =  [self.center_crop(image=a	,  size=a      ) for image in images]

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

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

       lowercase_						:     List[str]							     =  [to_channel_dimension_format(a	,  a      ) for image in images]

       lowercase_						:     Optional[int]							     =  {"pixel_values": images}
       return BatchFeature(data=a	,  tensor_type=a      )












'''simple docstring'''
import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
 from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
 from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
 from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


UpperCamelCase__			=      DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

UpperCamelCase__			=      'main'
# Default branch name
UpperCamelCase__			=      'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'
# One particular commit (not the top of `main`)
UpperCamelCase__			=      'aaaaaaa'
# This commit does not exist, so we should 404.

UpperCamelCase__			=      'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684'
# Sha-1 of config.json on the top of `main`, for checking purposes
UpperCamelCase__			=      '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'




@contextlib.contextmanager
def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   print("Welcome!"				)
   yield
   print("Bye!"				)




@contextlib.contextmanager
def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   print("Bonjour!"				)
   yield
   print("Au revoir!"				)


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       assert transformers.__spec__ is not None
       assert importlib.util.find_spec("transformers"      ) is not None


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							str	,  a	:							List[str]      ):






       '''simple docstring'''






       with ContextManagers([]      ):
          print("Transformers are awesome!"      )
       # The print statement adds a new line at the end of the output
       self.assertEqual(mock_stdout.getvalue()	,  "Transformers are awesome!\n"      )




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							List[str]	,  a	:							Optional[int]      ):






       '''simple docstring'''






       with ContextManagers([context_en()]      ):
          print("Transformers are awesome!"      )
       # The output should be wrapped with an English welcome and goodbye
       self.assertEqual(mock_stdout.getvalue()	,  "Welcome!\nTransformers are awesome!\nBye!\n"      )




    @unittest.mock.patch("sys.stdout"	,  new_callable=io.StringIO      )
    def 					lowerCAmelCase__					(      self	:							Tuple	,  a	:							List[Any]      ):






       '''simple docstring'''






       with ContextManagers([context_fr(), context_en()]      ):
          print("Transformers are awesome!"      )
       # The output should be wrapped with an English and French welcome and goodbye
       self.assertEqual(mock_stdout.getvalue()	,  "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n"      )




    @require_torch
    def 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  ["labels"]      )
       self.assertEqual(find_labels(a      )	,  ["labels", "next_sentence_label"]      )
       self.assertEqual(find_labels(a      )	,  ["start_positions", "end_positions"]      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  ["labels"]      )




    @require_tf
    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  ["labels"]      )
       self.assertEqual(find_labels(a      )	,  ["labels", "next_sentence_label"]      )
       self.assertEqual(find_labels(a      )	,  ["start_positions", "end_positions"]      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  ["labels"]      )





    @require_flax
    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






       self.assertEqual(find_labels(a      )	,  []      )
       self.assertEqual(find_labels(a      )	,  []      )
       self.assertEqual(find_labels(a      )	,  []      )


       class 							_UpperCAmelCase    (		snake_case      ):
           pass


       self.assertEqual(find_labels(a      )	,  []      )




