
"""simple docstring"""






import unittest

import numpy as np

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

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 DPTImageProcessor





class 				a__					(						unittest.TestCase       ):



     def __init__(							self :Union[str, Any]      ,  _lowerCamelCase :Tuple      ,  _lowerCamelCase :str=7      ,  _lowerCamelCase :Tuple=3      ,  _lowerCamelCase :List[str]=18      ,  _lowerCamelCase :int=30      ,  _lowerCamelCase :str=400      ,  _lowerCamelCase :int=True      ,  _lowerCamelCase :int=None      ,  _lowerCamelCase :List[str]=True      ,  _lowerCamelCase :Union[str, Any]=[0.5, 0.5, 0.5]      ,  _lowerCamelCase :Any=[0.5, 0.5, 0.5]      ,  ):







      '''simple docstring'''



      UpperCamelCase_     :					str   	=size if size is not None else {'height': 18, 'width': 18}
      UpperCamelCase_     :					Optional[int]   	=parent
      UpperCamelCase_     :					List[str]   	=batch_size
      UpperCamelCase_     :					Any   	=num_channels
      UpperCamelCase_     :					int   	=image_size
      UpperCamelCase_     :					Any   	=min_resolution
      UpperCamelCase_     :					int   	=max_resolution
      UpperCamelCase_     :					Dict   	=do_resize
      UpperCamelCase_     :					Optional[Any]   	=size
      UpperCamelCase_     :					Optional[Any]   	=do_normalize
      UpperCamelCase_     :					List[str]   	=image_mean
      UpperCamelCase_     :					List[Any]   	=image_std




     def  lowerCamelCase_						(							self :List[str]   ):







      '''simple docstring'''



      return {
          "image_mean": self.image_mean,
          "image_std": self.image_std,
          "do_normalize": self.do_normalize,
          "do_resize": self.do_resize,
          "size": self.size,
      }





@require_torch
@require_vision
class 				a__					(						__snake_case   ,							unittest.TestCase       ):
     UpperCAmelCase__         =      DPTImageProcessor if is_vision_available() else None



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[str]   	=DPTImageProcessingTester(self   )



     @property
     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



      return self.image_processor_tester.prepare_image_processor_dict()



     def  lowerCamelCase_						(							self :Tuple   ):







      '''simple docstring'''



      UpperCamelCase_     :					Dict   	=self.image_processing_class(**self.image_processor_dict   )
      self.assertTrue(hasattr(__lowerCamelCase      ,  'image_mean'   )   )
      self.assertTrue(hasattr(__lowerCamelCase      ,  'image_std'   )   )
      self.assertTrue(hasattr(__lowerCamelCase      ,  'do_normalize'   )   )
      self.assertTrue(hasattr(__lowerCamelCase      ,  'do_resize'   )   )
      self.assertTrue(hasattr(__lowerCamelCase      ,  'size'   )   )



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					List[Any]   	=self.image_processing_class.from_dict(self.image_processor_dict   )
      self.assertEqual(image_processor.size      ,  {'height': 18, 'width': 18}   )

      UpperCamelCase_     :					Any   	=self.image_processing_class.from_dict(self.image_processor_dict      ,  size=42   )
      self.assertEqual(image_processor.size      ,  {'height': 42, 'width': 42}   )



     def  lowerCamelCase_						(							self :Optional[int]   ):







      '''simple docstring'''



      UpperCamelCase_     :					int   	=self.image_processing_class(**self.image_processor_dict   )
      # create random PIL images
      UpperCamelCase_     :					str   	=prepare_image_inputs(self.image_processor_tester      ,  equal_resolution=__lowerCamelCase   )
      for image in image_inputs:
       self.assertIsInstance(__lowerCamelCase      ,  Image.Image   )

      # 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.size['height'],
              self.image_processor_tester.size['width'],
          )      ,  )

      # Test batched
      UpperCamelCase_     :					str   	=image_processing(__lowerCamelCase      ,  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.size['height'],
              self.image_processor_tester.size['width'],
          )      ,  )



     def  lowerCamelCase_						(							self :Optional[Any]   ):







      '''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=__lowerCamelCase      ,  numpify=__lowerCamelCase   )
      for image in image_inputs:
       self.assertIsInstance(__lowerCamelCase      ,  np.ndarray   )

      # Test not batched input
      UpperCamelCase_     :					List[Any]   	=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.size['height'],
              self.image_processor_tester.size['width'],
          )      ,  )

      # Test batched
      UpperCamelCase_     :					Optional[int]   	=image_processing(__lowerCamelCase      ,  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.size['height'],
              self.image_processor_tester.size['width'],
          )      ,  )




     def  lowerCamelCase_						(							self :List[Any]   ):







      '''simple docstring'''



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

      # Test not batched input
      UpperCamelCase_     :					int   	=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.size['height'],
              self.image_processor_tester.size['width'],
          )      ,  )

      # Test batched
      UpperCamelCase_     :					Union[str, Any]   	=image_processing(__lowerCamelCase      ,  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.size['height'],
              self.image_processor_tester.size['width'],
          )      ,  )




import copy
import os
from typing import Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__a	 =      logging.get_logger(__name__)

__a	 =      {
    """google/pix2struct-textcaps-base""": (
        """https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json"""
    ),
}






class 	__lowercase					(	__snake_case	):
      UpperCamelCase										=							'''pix2struct_text_model'''
      UpperCamelCase										=							['''past_key_values''']
      UpperCamelCase										=							{
          '''hidden_size''': '''hidden_size''',
          '''num_attention_heads''': '''num_heads''',
          '''num_hidden_layers''': '''num_layers''',
      }





      def __init__(		self    :       Optional[Any]       ,							__lowerCamelCase    :       Optional[int]=5_0_2_4_4       ,							__lowerCamelCase    :       int=7_6_8       ,							__lowerCamelCase    :       Union[str, Any]=6_4       ,							__lowerCamelCase    :       Dict=2_0_4_8       ,							__lowerCamelCase    :       int=1_2       ,							__lowerCamelCase    :       Any=1_2       ,							__lowerCamelCase    :       Union[str, Any]=3_2       ,							__lowerCamelCase    :       Any=1_2_8       ,							__lowerCamelCase    :       Union[str, Any]=0.1       ,							__lowerCamelCase    :       str=1e-6       ,							__lowerCamelCase    :       int=1.0       ,							__lowerCamelCase    :       Optional[int]="gelu_new"       ,							__lowerCamelCase    :       int=0       ,							__lowerCamelCase    :       int=False       ,							__lowerCamelCase    :       Optional[Any]=0       ,							__lowerCamelCase    :       Dict=1       ,							__lowerCamelCase    :       List[Any]=False       ,							__lowerCamelCase    :       Optional[Any]=True       ,							**__lowerCamelCase    :       Dict       ,							)     -> int:






         """simple docstring"""







         UpperCAmelCase      					=  vocab_size
         UpperCAmelCase      					=  hidden_size
         UpperCAmelCase      					=  d_kv
         UpperCAmelCase      					=  d_ff
         UpperCAmelCase      					=  num_layers
         UpperCAmelCase      					=  num_heads
         UpperCAmelCase      					=  relative_attention_num_buckets
         UpperCAmelCase      					=  relative_attention_max_distance
         UpperCAmelCase      					=  dropout_rate
         UpperCAmelCase      					=  layer_norm_epsilon
         UpperCAmelCase      					=  initializer_factor
         UpperCAmelCase      					=  use_cache

         UpperCAmelCase      					=  eos_token_id
         UpperCAmelCase      					=  decoder_start_token_id

         # for backwards compatibility
         UpperCAmelCase      					=  dense_act_fn

         super().__init__(
             pad_token_id=__lowerCamelCase       ,							eos_token_id=__lowerCamelCase       ,							decoder_start_token_id=__lowerCamelCase       ,							tie_word_embeddings=__lowerCamelCase       ,							is_decoder=__lowerCamelCase       ,							**__lowerCamelCase       ,							)





      @classmethod
      def 							_lowercase					(		cls    :       List[Any]       ,							__lowerCamelCase    :       Union[str, os.PathLike]       ,							**__lowerCamelCase    :       Any							)     -> "PretrainedConfig":






         """simple docstring"""







         cls._set_token_in_kwargs(__lowerCamelCase							)

         UpperCAmelCase					,	UpperCAmelCase      					=  cls.get_config_dict(__lowerCamelCase       ,							**__lowerCamelCase							)

         # get the text config dict if we are loading from Pix2StructConfig
         if config_dict.get("""model_type"""							) == "pix2struct":
            UpperCAmelCase      					=  config_dict["""text_config"""]

         if "model_type" in config_dict and hasattr(cls       ,							"""model_type"""							) and config_dict["model_type"] != cls.model_type:
            logger.warning(
                F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
                F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""							)

         return cls.from_dict(__lowerCamelCase       ,							**__lowerCamelCase							)






class 	__lowercase					(	__snake_case	):
      UpperCamelCase										=							'''pix2struct_vision_model'''





      def __init__(		self    :       str       ,							__lowerCamelCase    :       Any=7_6_8       ,							__lowerCamelCase    :       Dict=7_6_8       ,							__lowerCamelCase    :       List[Any]=2_0_4_8       ,							__lowerCamelCase    :       List[Any]=6_4       ,							__lowerCamelCase    :       Union[str, Any]=1_2       ,							__lowerCamelCase    :       Optional[int]=1_2       ,							__lowerCamelCase    :       Tuple="gelu_new"       ,							__lowerCamelCase    :       Tuple=1e-6       ,							__lowerCamelCase    :       Any=0.0       ,							__lowerCamelCase    :       List[Any]=0.0       ,							__lowerCamelCase    :       int=1e-1_0       ,							__lowerCamelCase    :       Union[str, Any]=1.0       ,							__lowerCamelCase    :       Any=4_0_9_6       ,							__lowerCamelCase    :       Dict=3_2       ,							__lowerCamelCase    :       Any=1_2_8       ,							**__lowerCamelCase    :       Optional[int]       ,							)     -> Optional[Any]:






         """simple docstring"""







         super().__init__(**__lowerCamelCase							)

         UpperCAmelCase      					=  hidden_size
         UpperCAmelCase      					=  patch_embed_hidden_size
         UpperCAmelCase      					=  d_ff
         UpperCAmelCase      					=  dropout_rate
         UpperCAmelCase      					=  num_hidden_layers
         UpperCAmelCase      					=  num_attention_heads
         UpperCAmelCase      					=  initializer_range
         UpperCAmelCase      					=  initializer_factor
         UpperCAmelCase      					=  attention_dropout
         UpperCAmelCase      					=  layer_norm_eps
         UpperCAmelCase      					=  dense_act_fn
         UpperCAmelCase      					=  seq_len
         UpperCAmelCase      					=  relative_attention_num_buckets
         UpperCAmelCase      					=  relative_attention_max_distance
         UpperCAmelCase      					=  d_kv





      @classmethod
      def 							_lowercase					(		cls    :       Any       ,							__lowerCamelCase    :       Union[str, os.PathLike]       ,							**__lowerCamelCase    :       int							)     -> "PretrainedConfig":






         """simple docstring"""







         cls._set_token_in_kwargs(__lowerCamelCase							)

         UpperCAmelCase					,	UpperCAmelCase      					=  cls.get_config_dict(__lowerCamelCase       ,							**__lowerCamelCase							)

         # get the vision config dict if we are loading from Pix2StructConfig
         if config_dict.get("""model_type"""							) == "pix2struct":
            UpperCAmelCase      					=  config_dict["""vision_config"""]

         if "model_type" in config_dict and hasattr(cls       ,							"""model_type"""							) and config_dict["model_type"] != cls.model_type:
            logger.warning(
                F"""You are using a model of type {config_dict['model_type']} to instantiate a model of type """
                F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors."""							)

         return cls.from_dict(__lowerCamelCase       ,							**__lowerCamelCase							)






class 	__lowercase					(	__snake_case	):
      UpperCamelCase										=							'''pix2struct'''
      UpperCamelCase										=							True





      def __init__(		self    :       str       ,							__lowerCamelCase    :       str=None       ,							__lowerCamelCase    :       Dict=None       ,							__lowerCamelCase    :       Optional[Any]=1.0       ,							__lowerCamelCase    :       str=0.02       ,							__lowerCamelCase    :       Any=False       ,							__lowerCamelCase    :       Tuple=False       ,							__lowerCamelCase    :       str=True       ,							**__lowerCamelCase    :       Dict       ,							)     -> Optional[Any]:






         """simple docstring"""







         super().__init__(tie_word_embeddings=__lowerCamelCase       ,							is_encoder_decoder=__lowerCamelCase       ,							**__lowerCamelCase							)

         if text_config is None:
            UpperCAmelCase      					=  {}
            logger.info("""text_config is None. Initializing the Pix2StructTextConfig with default values."""							)

         if vision_config is None:
            UpperCAmelCase      					=  {}
            logger.info("""vision_config is None. Initializing the Pix2StructVisionConfig with default values."""							)

         UpperCAmelCase      					=  PixaStructTextConfig(**__lowerCamelCase							)
         UpperCAmelCase      					=  PixaStructVisionConfig(**__lowerCamelCase							)

         UpperCAmelCase      					=  self.text_config.decoder_start_token_id
         UpperCAmelCase      					=  self.text_config.pad_token_id
         UpperCAmelCase      					=  self.text_config.eos_token_id

         UpperCAmelCase      					=  initializer_factor
         UpperCAmelCase      					=  initializer_range

         UpperCAmelCase      					=  self.initializer_range
         UpperCAmelCase      					=  self.initializer_range

         UpperCAmelCase      					=  is_vqa





      @classmethod
      def 							_lowercase					(		cls    :       List[Any]       ,							__lowerCamelCase    :       PixaStructTextConfig       ,							__lowerCamelCase    :       PixaStructVisionConfig       ,							**__lowerCamelCase    :       Dict							)     -> Union[str, Any]:






         """simple docstring"""







         return cls(text_config=text_config.to_dict()       ,							vision_config=vision_config.to_dict()       ,							**__lowerCamelCase							)





      def 							_lowercase					(		self    :       List[str]							)     -> Optional[int]:






         """simple docstring"""







         UpperCAmelCase      					=  copy.deepcopy(self.__dict__							)
         UpperCAmelCase      					=  self.text_config.to_dict()
         UpperCAmelCase      					=  self.vision_config.to_dict()
         UpperCAmelCase      					=  self.__class__.model_type
         return output



