
from typing import Dict, List, Optional, Union

import numpy as np

from transformers.utils import is_vision_available
from transformers.utils.generic import TensorType

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_valid_image,
    to_numpy_array,
    valid_images,
)
from ...utils import logging


if is_vision_available():
			import PIL

_lowerCamelCase       :				Optional[Any]       =			logging.get_logger(__name__)






def        a_		(       __lowercase   :	Dict ) ->  Any:





			if isinstance(UpperCamelCase__       ,					(list, tuple) ) and isinstance(videos[0]       ,					(list, tuple) ) and is_valid_image(videos[0][0] ):
						return videos

			elif isinstance(UpperCamelCase__       ,					(list, tuple) ) and is_valid_image(videos[0] ):
						return [videos]

			elif is_valid_image(UpperCamelCase__ ):
						return [[videos]]

			raise ValueError(f'''Could not make batched video from {videos}''' )




class    SCREAMING_SNAKE_CASE__     (	__A					):





	'''simple docstring'''



	_UpperCAmelCase       :		List[Any]       =					['pixel_values']



	def __init__(  self	:    Optional[int]			,  lowercase	:    Any = True			,  lowercase	:    Dict = None			,  lowercase	:    int = PILImageResampling.BILINEAR			,  lowercase	:    str = True			,  lowercase	:    Optional[int] = None			,  lowercase	:    Tuple = True			,  lowercase	:    int = 1 / 255			,  lowercase	:    Optional[int] = True			,  lowercase	:    Optional[int] = True			,  lowercase	:    List[Any] = None			,  lowercase	:    str = None			,  **lowercase	:    Tuple			,  ):


				'''simple docstring'''


				super().__init__(**__UpperCAmelCase	)
				_snake_case		=			size if size is not None else {'shortest_edge': 256}
				_snake_case		=			get_size_dict(__UpperCAmelCase			,  default_to_square=__UpperCAmelCase	)
				_snake_case		=			crop_size if crop_size is not None else {'height': 224, 'width': 224}
				_snake_case		=			get_size_dict(__UpperCAmelCase			,  param_name='crop_size'	)

				_snake_case		=			do_resize
				_snake_case		=			size
				_snake_case		=			do_center_crop
				_snake_case		=			crop_size
				_snake_case		=			resample
				_snake_case		=			do_rescale
				_snake_case		=			rescale_factor
				_snake_case		=			offset
				_snake_case		=			do_normalize
				_snake_case		=			image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
				_snake_case		=			image_std if image_std is not None else IMAGENET_STANDARD_STD



	def  A							(  self	:    str			,  lowercase	:    List[Any]			,  lowercase	:    int			,  lowercase	:    Dict = PILImageResampling.BILINEAR			,  lowercase	:    Optional[Any] = None			,  **lowercase	:    Optional[Any]			,  ):


				'''simple docstring'''


				_snake_case		=			get_size_dict(__UpperCAmelCase			,  default_to_square=__UpperCAmelCase	)
				if "shortest_edge" in size:
							_snake_case		=			get_resize_output_image_size(__UpperCAmelCase			,  size['shortest_edge']			,  default_to_square=__UpperCAmelCase	)
				elif "height" in size and "width" in size:
							_snake_case		=			(size['height'], size['width'])
				else:
							raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''	)
				return resize(__UpperCAmelCase			,  size=__UpperCAmelCase			,  resample=__UpperCAmelCase			,  data_format=__UpperCAmelCase			,  **__UpperCAmelCase	)



	def  A							(  self	:    Optional[Any]			,  lowercase	:    Dict			,  lowercase	:    Optional[int]			,  lowercase	:    Tuple = None			,  **lowercase	:    Dict			,  ):


				'''simple docstring'''


				_snake_case		=			get_size_dict(__UpperCAmelCase	)
				if "height" not in size or "width" not in size:
							raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}'''	)
				return center_crop(__UpperCAmelCase			,  size=(size['height'], size['width'])			,  data_format=__UpperCAmelCase			,  **__UpperCAmelCase	)



	def  A							(  self	:    Union[str, Any]			,  lowercase	:    str			,  lowercase	:    str			,  lowercase	:    Any = True			,  lowercase	:    List[Any] = None			,  **lowercase	:    Optional[Any]			,  ):


				'''simple docstring'''


				_snake_case		=			image.astype(np.floataa	)
				if offset:
							_snake_case		=			image - (scale / 2)
				return rescale(__UpperCAmelCase			,  scale=__UpperCAmelCase			,  data_format=__UpperCAmelCase			,  **__UpperCAmelCase	)



	def  A							(  self	:    List[Any]			,  lowercase	:    str			,  lowercase	:    str			,  lowercase	:    str			,  lowercase	:    str = None			,  **lowercase	:    Optional[int]			,  ):


				'''simple docstring'''


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



	def  A							(  self	:    Dict			,  lowercase	:    int			,  lowercase	:    str = None			,  lowercase	:    Optional[Any] = None			,  lowercase	:    int = None			,  lowercase	:    str = None			,  lowercase	:    Dict = None			,  lowercase	:    Optional[int] = None			,  lowercase	:    Any = None			,  lowercase	:    str = None			,  lowercase	:    Optional[Any] = None			,  lowercase	:    List[str] = None			,  lowercase	:    Dict = None			,  lowercase	:    List[str] = ChannelDimension.FIRST			,  ):


				'''simple docstring'''


				if do_resize and size is None or resample is None:
							raise ValueError('Size and resample 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.'	)

				if offset and not do_rescale:
							raise ValueError('For offset, do_rescale must also be set to True.'	)

				# All transformations expect numpy arrays.
				_snake_case		=			to_numpy_array(__UpperCAmelCase	)

				if do_resize:
							_snake_case		=			self.resize(image=__UpperCAmelCase			,  size=__UpperCAmelCase			,  resample=__UpperCAmelCase	)

				if do_center_crop:
							_snake_case		=			self.center_crop(__UpperCAmelCase			,  size=__UpperCAmelCase	)

				if do_rescale:
							_snake_case		=			self.rescale(image=__UpperCAmelCase			,  scale=__UpperCAmelCase			,  offset=__UpperCAmelCase	)

				if do_normalize:
							_snake_case		=			self.normalize(image=__UpperCAmelCase			,  mean=__UpperCAmelCase			,  std=__UpperCAmelCase	)

				_snake_case		=			to_channel_dimension_format(__UpperCAmelCase			,  __UpperCAmelCase	)
				return image





	def  A							(  self	:    List[Any]			,  lowercase	:    Tuple			,  lowercase	:    str = None			,  lowercase	:    List[Any] = None			,  lowercase	:    List[str] = None			,  lowercase	:    Optional[int] = None			,  lowercase	:    Optional[Any] = None			,  lowercase	:    Union[str, Any] = None			,  lowercase	:    Union[str, Any] = None			,  lowercase	:    Tuple = None			,  lowercase	:    str = None			,  lowercase	:    List[Any] = None			,  lowercase	:    Optional[Any] = None			,  lowercase	:    Optional[int] = None			,  lowercase	:    Union[str, Any] = ChannelDimension.FIRST			,  **lowercase	:    Tuple			,  ):


				'''simple docstring'''


				_snake_case		=			do_resize if do_resize is not None else self.do_resize
				_snake_case		=			resample if resample is not None else self.resample
				_snake_case		=			do_center_crop if do_center_crop is not None else self.do_center_crop
				_snake_case		=			do_rescale if do_rescale is not None else self.do_rescale
				_snake_case		=			rescale_factor if rescale_factor is not None else self.rescale_factor
				_snake_case		=			offset if offset is not None else self.offset
				_snake_case		=			do_normalize if do_normalize is not None else self.do_normalize
				_snake_case		=			image_mean if image_mean is not None else self.image_mean
				_snake_case		=			image_std if image_std is not None else self.image_std

				_snake_case		=			size if size is not None else self.size
				_snake_case		=			get_size_dict(__UpperCAmelCase			,  default_to_square=__UpperCAmelCase	)
				_snake_case		=			crop_size if crop_size is not None else self.crop_size
				_snake_case		=			get_size_dict(__UpperCAmelCase			,  param_name='crop_size'	)

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

				_snake_case		=			make_batched(__UpperCAmelCase	)

				_snake_case		=			[
				    [
				        self._preprocess_image(
				            image=__UpperCAmelCase			,  do_resize=__UpperCAmelCase			,  size=__UpperCAmelCase			,  resample=__UpperCAmelCase			,  do_center_crop=__UpperCAmelCase			,  crop_size=__UpperCAmelCase			,  do_rescale=__UpperCAmelCase			,  rescale_factor=__UpperCAmelCase			,  offset=__UpperCAmelCase			,  do_normalize=__UpperCAmelCase			,  image_mean=__UpperCAmelCase			,  image_std=__UpperCAmelCase			,  data_format=__UpperCAmelCase			,  )
				        for img in video
				    ]
				    for video in videos
				]

				_snake_case		=			{'pixel_values': videos}
				return BatchFeature(data=__UpperCAmelCase			,  tensor_type=__UpperCAmelCase	)
"""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


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

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

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






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Welcome!' )
							yield
							print('Bye!' )






@contextlib.contextmanager
def      UpperCAmelCase    (		):






							"""simple docstring"""





							print('Bonjour!' )
							yield
							print('Au revoir!' )
class 			UpperCamelCase__(	unittest.TestCase       ):





						def  snake_case__		(				self   )    -> List[str]:
													# If the spec is missing, importlib would not be able to import the module dynamically.
													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  snake_case__		(				self						,__UpperCAmelCase   )    -> Dict:
													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  snake_case__		(				self						,__UpperCAmelCase   )    -> List[str]:
													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  snake_case__		(				self						,__UpperCAmelCase   )    -> Any:
													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  snake_case__		(				self   )    -> Union[str, Any]:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_tf
						def  snake_case__		(				self   )    -> str:
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels', 'next_sentence_label']   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,['start_positions', 'end_positions']   )
													class 			UpperCamelCase__(	__A       ):
																			pass






													self.assertEqual(find_labels(__UpperCAmelCase   )						,['labels']   )





						@require_flax
						def  snake_case__		(				self   )    -> List[Any]:
													# Flax models don't have labels
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													self.assertEqual(find_labels(__UpperCAmelCase   )						,[]   )
													class 			UpperCamelCase__(	__A       ):
																			pass






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





