






import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


UpperCAmelCase__      			=						get_logger(__name__)


UpperCAmelCase__      			=						r'''\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n'''




class 							snake_case_       :

						"""simple docstring"""



						@add_start_docstrings(a__   )
						def __call__(self:					Optional[int] ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					Union[str, Any]   )    ->     Any:




											'''simple docstring'''



											raise NotImplementedError(
											    f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.'   )




class 							snake_case_       :

						"""simple docstring"""



						@add_start_docstrings(a__   )
						def __call__(self:					Dict ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					Union[str, Any]   )    ->     Dict:




											'''simple docstring'''



											raise NotImplementedError(
											    f'{self.__class__} is an abstract class. Only classes inheriting this class can be called.'   )




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						@add_start_docstrings(a__   )
						def __call__(self:					List[str] ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					str ,					**__UpperCAmelCase:					str   )    ->     int:




											'''simple docstring'''



											for processor in self:
																__a					:						Union[str, Any]      =					inspect.signature(processor.__call__   ).parameters
																if len(a__   ) > 3:
																					if not all(arg in kwargs for arg in list(function_args.keys()   )[2:]   ):
																										raise ValueError(
																										    f'Make sure that all the required parameters: {list(function_args.keys()   )} for '
																										    f'{processor.__class__} are passed to the logits processor.'   )
																					__a					:						Tuple      =					processor(a__ ,					a__ ,					a__ ,					**a__   )
																else:
																					__a					:						Optional[int]      =					processor(a__ ,					a__ ,					a__   )
											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					List[str] ,					__UpperCAmelCase:					Optional[Any]   )    ->     Optional[int]:




											'''simple docstring'''



											if not isinstance(a__ ,					a__   ) or not (temperature > 0):
																raise ValueError(f'`temperature` has to be a strictly positive float, but is {temperature}'   )

											__a					:						Tuple      =					temperature



						def __call__(self:					Tuple ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					Dict   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						Any      =					scores / self.temperature
											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					List[Any] ,					__UpperCAmelCase:					Any ,					__UpperCAmelCase:					Optional[int] = -float("Inf"   ) ,					__UpperCAmelCase:					List[str] = 1   )    ->     Optional[int]:




											'''simple docstring'''



											if not isinstance(a__ ,					a__   ) or (top_p < 0 or top_p > 1.0):
																raise ValueError(f'`top_p` has to be a float > 0 and < 1, but is {top_p}'   )
											if not isinstance(a__ ,					a__   ) or (min_tokens_to_keep < 1):
																raise ValueError(f'`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}'   )

											__a					:						int      =					top_p
											__a					:						Union[str, Any]      =					filter_value
											__a					:						Optional[Any]      =					min_tokens_to_keep



						def __call__(self:					List[str] ,					__UpperCAmelCase:					Tuple ,					__UpperCAmelCase:					Optional[int] ,					__UpperCAmelCase:					Tuple   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						int      =					lax.top_k(a__ ,					scores.shape[-1]   )

											__a					:						int      =					jnp.full_like(a__ ,					self.filter_value   )
											__a					:						Optional[int]      =					jax.nn.softmax(a__ ,					axis=-1   ).cumsum(axis=-1   )
											__a					:						List[Any]      =					cumulative_probs < self.top_p

											# include the token that is higher than top_p as well
											__a					:						Optional[Any]      =					jnp.roll(a__ ,					1   )
											score_mask |= score_mask.at[:, 0].set(a__   )

											# min tokens to keep
											__a					:						str      =					score_mask.at[:, : self.min_tokens_to_keep].set(a__   )

											__a					:						int      =					jnp.where(a__ ,					a__ ,					a__   )
											__a					:						Any      =					jax.lax.sort_key_val(a__ ,					a__   )[-1]

											return next_scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					Dict ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					List[Any] = -float("Inf"   ) ,					__UpperCAmelCase:					Any = 1   )    ->     Any:




											'''simple docstring'''



											if not isinstance(a__ ,					a__   ) or top_k <= 0:
																raise ValueError(f'`top_k` has to be a strictly positive integer, but is {top_k}'   )

											__a					:						List[Any]      =					max(a__ ,					a__   )
											__a					:						Union[str, Any]      =					filter_value



						def __call__(self:					Dict ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					Optional[int]   )    ->     List[str]:




											'''simple docstring'''



											__a					:						List[Any]      =					scores.shape
											__a					:						List[Any]      =					jnp.full(batch_size * vocab_size ,					self.filter_value   )

											__a					:						Union[str, Any]      =					min(self.top_k ,					scores.shape[-1]   )  # Safety check
											__a					:						int      =					lax.top_k(a__ ,					a__   )
											__a					:						int      =					jnp.broadcast_to((jnp.arange(a__   ) * vocab_size)[:, None] ,					(batch_size, topk)   ).flatten()
											__a					:						List[Any]      =					topk_scores.flatten()
											__a					:						Any      =					topk_indices.flatten() + shift

											__a					:						str      =					next_scores_flat.at[topk_indices_flat].set(a__   )
											__a					:						Optional[int]      =					next_scores_flat.reshape(a__ ,					a__   )
											return next_scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					Union[str, Any] ,					__UpperCAmelCase:					Any   )    ->     Dict:




											'''simple docstring'''



											__a					:						Dict      =					bos_token_id



						def __call__(self:					Tuple ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					Any ,					__UpperCAmelCase:					Dict   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						List[str]      =					jnp.full(scores.shape ,					-float("inf"   )   )

											__a					:						Dict      =					1 - jnp.bool_(cur_len - 1   )

											__a					:						List[str]      =					jnp.where(a__ ,					new_scores.at[:, self.bos_token_id].set(0   ) ,					a__   )

											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					Union[str, Any] ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					str   )    ->     Optional[Any]:




											'''simple docstring'''



											__a					:						List[str]      =					max_length
											__a					:						Any      =					eos_token_id



						def __call__(self:					Union[str, Any] ,					__UpperCAmelCase:					Any ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					List[Any]   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						List[Any]      =					jnp.full(scores.shape ,					-float("inf"   )   )

											__a					:						Any      =					1 - jnp.bool_(cur_len - self.max_length + 1   )

											__a					:						List[str]      =					jnp.where(a__ ,					new_scores.at[:, self.eos_token_id].set(0   ) ,					a__   )

											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					Optional[int] ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					Optional[int]   )    ->     Union[str, Any]:




											'''simple docstring'''



											if not isinstance(a__ ,					a__   ) or min_length < 0:
																raise ValueError(f'`min_length` has to be a positive integer, but is {min_length}'   )

											if not isinstance(a__ ,					a__   ) or eos_token_id < 0:
																raise ValueError(f'`eos_token_id` has to be a positive integer, but is {eos_token_id}'   )

											__a					:						List[Any]      =					min_length
											__a					:						Any      =					eos_token_id



						def __call__(self:					Optional[Any] ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					int   )    ->     List[str]:




											'''simple docstring'''



											__a					:						Tuple      =					1 - jnp.clip(cur_len - self.min_length ,					0 ,					1   )

											__a					:						int      =					jnp.where(a__ ,					scores.at[:, self.eos_token_id].set(-float("inf"   )   ) ,					a__   )

											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					str ,					__UpperCAmelCase:					Optional[int] ,					__UpperCAmelCase:					Any   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						int      =					list(a__   )
											__a					:						Union[str, Any]      =					begin_index



						def __call__(self:					List[Any] ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					List[Any] ,					__UpperCAmelCase:					List[str]   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						List[Any]      =					1 - jnp.bool_(cur_len - self.begin_index   )

											__a					:						Dict      =					jnp.where(a__ ,					scores.at[:, self.begin_suppress_tokens].set(-float("inf"   )   ) ,					a__   )

											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					List[str] ,					__UpperCAmelCase:					str   )    ->     Optional[int]:




											'''simple docstring'''



											__a					:						Union[str, Any]      =					list(a__   )



						def __call__(self:					Any ,					__UpperCAmelCase:					Any ,					__UpperCAmelCase:					Dict ,					__UpperCAmelCase:					Dict   )    ->     int:




											'''simple docstring'''



											__a					:						Optional[Any]      =					scores.at[..., self.suppress_tokens].set(-float("inf"   )   )

											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					List[Any] ,					__UpperCAmelCase:					Tuple   )    ->     List[Any]:




											'''simple docstring'''



											__a					:						List[Any]      =					dict(a__   )
											# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
											# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
											# Indexes without forced tokens will have a negative value.
											__a					:						List[str]      =					jnp.ones((max(force_token_map.keys()   ) + 1) ,					dtype=jnp.intaa   ) * -1
											for index, token in force_token_map.items():
																if token is not None:
																					__a					:						List[Any]      =					force_token_array.at[index].set(a__   )
											__a					:						Tuple      =					jnp.intaa(a__   )



						def __call__(self:					str ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					str ,					__UpperCAmelCase:					str   )    ->     Union[str, Any]:




											'''simple docstring'''



											def _force_token(__UpperCAmelCase:					Dict   ):
																__a					:						Any      =					scores.shape[0]
																__a					:						Tuple      =					self.force_token_array[generation_idx]

																__a					:						Dict      =					jnp.ones_like(a__ ,					dtype=scores.dtype   ) * -float("inf"   )
																__a					:						List[Any]      =					jnp.zeros((batch_size, 1) ,					dtype=scores.dtype   )
																__a					:						Optional[int]      =					lax.dynamic_update_slice(a__ ,					a__ ,					(0, current_token)   )
																return new_scores

											__a					:						Any      =					lax.cond(
											    cur_len >= self.force_token_array.shape[0] ,					lambda: scores ,					lambda: lax.cond(
											        self.force_token_array[cur_len] >= 0 ,					lambda: _force_token(a__   ) ,					lambda: scores ,					) ,					)
											return scores




class 							snake_case_       (    lowerCamelCase__      ):

						"""simple docstring"""



						def __init__(self:					List[str] ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					List[str] ,					__UpperCAmelCase:					int   )    ->     Dict:




											'''simple docstring'''



											__a					:						str      =					generate_config.eos_token_id
											__a					:						List[str]      =					generate_config.no_timestamps_token_id
											__a					:						str      =					generate_config.no_timestamps_token_id + 1

											__a					:						List[Any]      =					decoder_input_length + 1

											if generate_config.is_multilingual:
																# room for language token and task token
																self.begin_index += 2
											if hasattr(a__ ,					"max_initial_timestamp_index"   ):
																__a					:						str      =					generate_config.max_initial_timestamp_index
											else:
																__a					:						List[str]      =					model_config.vocab_size
											if self.max_initial_timestamp_index is None:
																__a					:						Dict      =					model_config.vocab_size



						def __call__(self:					str ,					__UpperCAmelCase:					int ,					__UpperCAmelCase:					Optional[Any] ,					__UpperCAmelCase:					Tuple   )    ->     Union[str, Any]:




											'''simple docstring'''



											__a					:						List[Any]      =					scores.at[:, self.no_timestamps_token_id].set(-float("inf"   )   )

											def handle_pairs(__UpperCAmelCase:					Union[str, Any] ,					__UpperCAmelCase:					Dict   ):
																__a					:						Optional[Any]      =					jnp.where((cur_len - self.begin_index) >= 1 ,					a__ ,					a__   )
																__a					:						int      =					jnp.where(
																    input_ids_k[cur_len - 1] >= self.timestamp_begin ,					True and last_was_timestamp ,					a__ ,					)

																__a					:						Tuple      =					jnp.where((cur_len - self.begin_index) < 2 ,					a__ ,					a__   )
																__a					:						int      =					jnp.where(
																    input_ids_k[cur_len - 2] >= self.timestamp_begin ,					a__ ,					a__ ,					)

																return jnp.where(
																    a__ ,					jnp.where(
																        penultimate_was_timestamp > 0 ,					scores_k.at[self.timestamp_begin :].set(-float("inf"   )   ) ,					scores_k.at[: self.eos_token_id].set(-float("inf"   )   ) ,					) ,					a__ ,					)

											__a					:						Any      =					jax.vmap(a__   )(a__ ,					a__   )

											__a					:						Any      =					jnp.where(cur_len == self.begin_index ,					a__ ,					a__   )
											__a					:						Any      =					jnp.where(
											    self.max_initial_timestamp_index is not None ,					True and apply_max_initial_timestamp ,					a__ ,					)

											__a					:						List[Any]      =					self.timestamp_begin + self.max_initial_timestamp_index

											__a					:						str      =					jnp.where(
											    a__ ,					scores.at[:, last_allowed + 1 :].set(-float("inf"   )   ) ,					a__ ,					)

											# if sum of probability over timestamps is above any other token, sample timestamp
											__a					:						str      =					jax.nn.log_softmax(a__ ,					axis=-1   )

											def handle_cumulative_probs(__UpperCAmelCase:					int ,					__UpperCAmelCase:					Optional[int]   ):
																__a					:						Any      =					jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] ,					axis=-1   )
																__a					:						str      =					jnp.max(logprobs_k[: self.timestamp_begin]   )
																return jnp.where(
																    timestamp_logprob > max_text_token_logprob ,					scores_k.at[: self.timestamp_begin].set(-float("inf"   )   ) ,					a__ ,					)

											__a					:						List[Any]      =					jax.vmap(a__   )(a__ ,					a__   )

											return scores












import unittest

import numpy as np
import requests

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

       from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
       _lowerCamelCase      							=   False

if is_vision_available():
       from PIL import Image

       from transformers import PixaStructImageProcessor







class       __A							(   unittest.TestCase	):




      """simple docstring"""







      def __init__(		self   ,				a__   ,				a__=7   ,				a__=3   ,				a__=18   ,				a__=30   ,				a__=400   ,				a__=None   ,				a__=True   ,				a__=True   ,				a__=None   ,				):



             """simple docstring"""





             _lowerCamelCase				:  str						=		size if size is not None else {'''height''': 20, '''width''': 20}
             _lowerCamelCase				:  int						=		parent
             _lowerCamelCase				:  Tuple						=		batch_size
             _lowerCamelCase				:  Union[str, Any]						=		num_channels
             _lowerCamelCase				:  Tuple						=		image_size
             _lowerCamelCase				:  Dict						=		min_resolution
             _lowerCamelCase				:  int						=		max_resolution
             _lowerCamelCase				:  Dict						=		size
             _lowerCamelCase				:  Dict						=		do_normalize
             _lowerCamelCase				:  List[Any]						=		do_convert_rgb
             _lowerCamelCase				:  Optional[int]						=		[512, 1024, 2048, 4096]
             _lowerCamelCase				:  Optional[int]						=		patch_size if patch_size is not None else {'''height''': 16, '''width''': 16}


      def 					__snake_case      (		self):



             """simple docstring"""





             return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		'''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'''
             _lowerCamelCase				:  Union[str, Any]						=		Image.open(requests.get(a__   ,				stream=a__).raw).convert('''RGB''')
             return raw_image







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11			,reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""			,)
@require_torch
@require_vision
class       __A							(   lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		PixaStructImageProcessingTester(self)


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  int						=		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(a__   ,				'''do_normalize'''))
             self.assertTrue(hasattr(a__   ,				'''do_convert_rgb'''))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.image_processor_tester.prepare_dummy_image()

             _lowerCamelCase				:  List[Any]						=		self.image_processing_class(**self.image_processor_dict)
             _lowerCamelCase				:  Optional[int]						=		2048

             _lowerCamelCase				:  Any						=		image_processor(a__   ,				return_tensors='''pt'''   ,				max_patches=a__)
             self.assertTrue(torch.allclose(inputs.flattened_patches.mean()   ,				torch.tensor(0.0606)   ,				atol=1e-3   ,				rtol=1e-3))


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Dict						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  Any						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				Image.Image)

             # Test not batched input
             _lowerCamelCase				:  Optional[Any]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  Optional[int]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Dict						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)


      def 					__snake_case      (		self):



             """simple docstring"""





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

             # Test not batched input
             _lowerCamelCase				:  List[str]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             _lowerCamelCase				:  Dict						=		True

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    with self.assertRaises(a__):
                           _lowerCamelCase				:  List[Any]						=		image_processor(
                               image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches

                    _lowerCamelCase				:  List[Any]						=		'''Hello'''

                    _lowerCamelCase				:  int						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__   ,				header_text=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Dict						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__   ,				header_text=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		self.image_processing_class(**self.image_processor_dict)
             # create random numpy tensors
             _lowerCamelCase				:  Tuple						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__   ,				numpify=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				np.ndarray)

             _lowerCamelCase				:  Any						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  List[str]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Tuple						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		self.image_processing_class(**self.image_processor_dict)
             # create random PyTorch tensors
             _lowerCamelCase				:  str						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__   ,				torchify=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				torch.Tensor)

             # Test not batched input
             _lowerCamelCase				:  Tuple						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * self.image_processor_tester.num_channels
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  Optional[int]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  List[str]						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)







@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11			,reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`."""			,)
@require_torch
@require_vision
class       __A							(   lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   PixaStructImageProcessor if is_vision_available() else None


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Optional[Any]						=		PixaStructImageProcessingTester(self   ,				num_channels=4)
             _lowerCamelCase				:  Union[str, Any]						=		3


      @property
      def 					__snake_case      (		self):



             """simple docstring"""





             return self.image_processor_tester.prepare_image_processor_dict()


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  str						=		self.image_processing_class(**self.image_processor_dict)
             self.assertTrue(hasattr(a__   ,				'''do_normalize'''))
             self.assertTrue(hasattr(a__   ,				'''do_convert_rgb'''))



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		self.image_processing_class(**self.image_processor_dict)
             # create random PIL images
             _lowerCamelCase				:  Any						=		prepare_image_inputs(self.image_processor_tester   ,				equal_resolution=a__)
             for image in image_inputs:
                    self.assertIsInstance(a__   ,				Image.Image)

             # Test not batched input
             _lowerCamelCase				:  List[Any]						=		(
                 (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width'''])
                 * (self.image_processor_tester.num_channels - 1)
             ) + 2

             for max_patch in self.image_processor_tester.max_patches:
                    # Test not batched input
                    _lowerCamelCase				:  Union[str, Any]						=		image_processor(
                        image_inputs[0]   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(1, max_patch, expected_hidden_dim)   ,				)

                    # Test batched
                    _lowerCamelCase				:  Union[str, Any]						=		image_processor(
                        a__   ,				return_tensors='''pt'''   ,				max_patches=a__).flattened_patches
                    self.assertEqual(
                        encoded_images.shape   ,				(self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)   ,				)

