
"""simple docstring"""




import copy
import os
from typing import Union

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


A__ :       Dict				= logging.get_logger(__name__)

A__ :       Dict				= {
    'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''altclip_text_model'''
       def __init__(  self			,					A_=25_0002			,					A_=1024			,					A_=24			,					A_=16			,					A_=4096			,					A_="gelu"			,					A_=0.1			,					A_=0.1			,					A_=514			,					A_=1			,					A_=0.02			,					A_=0.02			,					A_=1E-05			,					A_=1			,					A_=0			,					A_=2			,					A_="absolute"			,					A_=True			,					A_=768			,					**A_			,					)  ->						List[str]:





         """simple docstring"""




         super().__init__(pad_token_id=A_			,					bos_token_id=A_			,					eos_token_id=A_			,					**A_							)

         _lowercase:      Any   			=  vocab_size
         _lowercase:      Optional[int]   			=  hidden_size
         _lowercase:      Any   			=  num_hidden_layers
         _lowercase:      List[Any]   			=  num_attention_heads
         _lowercase:      Any   			=  hidden_act
         _lowercase:      Tuple   			=  intermediate_size
         _lowercase:      Optional[int]   			=  hidden_dropout_prob
         _lowercase:      str   			=  attention_probs_dropout_prob
         _lowercase:      str   			=  max_position_embeddings
         _lowercase:      Any   			=  type_vocab_size
         _lowercase:      int   			=  initializer_range
         _lowercase:      Optional[int]   			=  initializer_factor
         _lowercase:      Union[str, Any]   			=  layer_norm_eps
         _lowercase:      str   			=  position_embedding_type
         _lowercase:      Any   			=  use_cache
         _lowercase:      Any   			=  project_dim


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''altclip_vision_model'''
       def __init__(  self			,					A_=768			,					A_=3072			,					A_=512			,					A_=12			,					A_=12			,					A_=3			,					A_=224			,					A_=32			,					A_="quick_gelu"			,					A_=1E-5			,					A_=0.0			,					A_=0.02			,					A_=1.0			,					**A_			,					)  ->						str:





         """simple docstring"""




         super().__init__(**A_							)

         _lowercase:      Optional[Any]   			=  hidden_size
         _lowercase:      Optional[Any]   			=  intermediate_size
         _lowercase:      Any   			=  projection_dim
         _lowercase:      Union[str, Any]   			=  num_hidden_layers
         _lowercase:      Any   			=  num_attention_heads
         _lowercase:      int   			=  num_channels
         _lowercase:      Dict   			=  patch_size
         _lowercase:      Tuple   			=  image_size
         _lowercase:      Tuple   			=  initializer_range
         _lowercase:      Dict   			=  initializer_factor
         _lowercase:      List[str]   			=  attention_dropout
         _lowercase:      Optional[int]   			=  layer_norm_eps
         _lowercase:      Any   			=  hidden_act



       @classmethod
       def 				lowercase_				(  cls			,					A_			,					**A_							)  ->						"PretrainedConfig":





         """simple docstring"""




         cls._set_token_in_kwargs(A_							)

         _lowercase			,					_lowercase:      Any   			=  cls.get_config_dict(A_			,					**A_							)

         # get the vision config dict if we are loading from AltCLIPConfig
         if config_dict.get('''model_type'''							) == "altclip":
           _lowercase:      int   			=  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(A_			,					**A_							)


class       __magic_name__							(							SCREAMING_SNAKE_CASE__			):
       UpperCamelCase_ =		'''altclip'''
       UpperCamelCase_ =		True
       def __init__(  self			,					A_=None			,					A_=None			,					A_=768			,					A_=2.65_92			,					**A_							)  ->						Dict:





         """simple docstring"""




         _lowercase:      Union[str, Any]   			=  kwargs.pop('''text_config_dict'''			,					A_							)
         _lowercase:      Tuple   			=  kwargs.pop('''vision_config_dict'''			,					A_							)

         super().__init__(**A_							)

         # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
         # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
         # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
         if text_config_dict is not None:
           if text_config is None:
             _lowercase:      str   			=  {}

           # This is the complete result when using `text_config_dict`.
           _lowercase:      Dict   			=  AltCLIPTextConfig(**A_							).to_dict()

           # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
           for key, value in _text_config_dict.items():
             if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
               # If specified in `text_config_dict`
               if key in text_config_dict:
                 _lowercase:      List[Any]   			=  (
                     f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
                     f'''The value `text_config_dict["{key}"]` will be used instead.'''
                 )
               # If inferred from default argument values (just to be super careful)
               else:
                 _lowercase:      Tuple   			=  (
                     f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
                     f'''value `text_config["{key}"]` will be overriden.'''
                 )
               logger.warning(A_							)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
           text_config.update(_text_config_dict							)

         if vision_config_dict is not None:
           if vision_config is None:
             _lowercase:      Union[str, Any]   			=  {}

           # This is the complete result when using `vision_config_dict`.
           _lowercase:      List[Any]   			=  AltCLIPVisionConfig(**A_							).to_dict()
           # convert keys to string instead of integer
           if "id2label" in _vision_config_dict:
             _lowercase:      Tuple   			=  {
                 str(A_							): value for key, value in _vision_config_dict['''id2label'''].items()
             }

           # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
           for key, value in _vision_config_dict.items():
             if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
               # If specified in `vision_config_dict`
               if key in vision_config_dict:
                 _lowercase:      Tuple   			=  (
                     f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
                     f'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
                 )
               # If inferred from default argument values (just to be super careful)
               else:
                 _lowercase:      List[Any]   			=  (
                     f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
                     f'''The value `vision_config["{key}"]` will be overriden.'''
                 )
               logger.warning(A_							)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
           vision_config.update(_vision_config_dict							)

         if text_config is None:
           _lowercase:      List[str]   			=  {}
           logger.info('''`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.'''							)

         if vision_config is None:
           _lowercase:      Optional[Any]   			=  {}
           logger.info('''`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.'''							)

         _lowercase:      str   			=  AltCLIPTextConfig(**A_							)
         _lowercase:      List[str]   			=  AltCLIPVisionConfig(**A_							)

         _lowercase:      Any   			=  projection_dim
         _lowercase:      Tuple   			=  logit_scale_init_value
         _lowercase:      Tuple   			=  1.0
       @classmethod
       def 				lowercase_				(  cls			,					A_			,					A_			,					**A_							)  ->						Any:





         """simple docstring"""




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



       def 				lowercase_				(  self							)  ->						Dict:





         """simple docstring"""




         _lowercase:      str   			=  copy.deepcopy(self.__dict__							)
         _lowercase:      str   			=  self.text_config.to_dict()
         _lowercase:      List[Any]   			=  self.vision_config.to_dict()
         _lowercase:      List[str]   			=  self.__class__.model_type
         return output


"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import is_flaky, 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

if is_vision_available():
  from PIL import Image

  from transformers import DonutImageProcessor


class       __magic_name__							(							unittest.TestCase			):
       def __init__(  self			,					A_			,					A_=7			,					A_=3			,					A_=18			,					A_=30			,					A_=400			,					A_=True			,					A_=None			,					A_=True			,					A_=False			,					A_=True			,					A_=True			,					A_=[0.5, 0.5, 0.5]			,					A_=[0.5, 0.5, 0.5]			,					)  ->						Optional[int]:





         """simple docstring"""




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



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





         """simple docstring"""




         return {
             "do_resize": self.do_resize,
             "size": self.size,
             "do_thumbnail": self.do_thumbnail,
             "do_align_long_axis": self.do_align_axis,
             "do_pad": self.do_pad,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
         }


@require_torch
@require_vision
class       __magic_name__							(							SCREAMING_SNAKE_CASE__ ,       unittest.TestCase			):
       UpperCamelCase_ =		DonutImageProcessor if is_vision_available() else None
       def 				lowercase_				(  self							)  ->						Optional[int]:





         """simple docstring"""




         _lowercase:      str   			=  DonutImageProcessingTester(self							)
       @property
       def 				lowercase_				(  self							)  ->						int:





         """simple docstring"""




         return self.image_processor_tester.prepare_image_processor_dict()
       def 				lowercase_				(  self							)  ->						Dict:





         """simple docstring"""




         _lowercase:      Optional[int]   			=  self.image_processing_class(**self.image_processor_dict							)
         self.assertTrue(hasattr(A_			,					'''do_resize'''							)							)
         self.assertTrue(hasattr(A_			,					'''size'''							)							)
         self.assertTrue(hasattr(A_			,					'''do_thumbnail'''							)							)
         self.assertTrue(hasattr(A_			,					'''do_align_long_axis'''							)							)
         self.assertTrue(hasattr(A_			,					'''do_pad'''							)							)
         self.assertTrue(hasattr(A_			,					'''do_normalize'''							)							)
         self.assertTrue(hasattr(A_			,					'''image_mean'''							)							)
         self.assertTrue(hasattr(A_			,					'''image_std'''							)							)
       def 				lowercase_				(  self							)  ->						List[Any]:





         """simple docstring"""




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

         _lowercase:      List[str]   			=  self.image_processing_class.from_dict(self.image_processor_dict			,					size=42							)
         self.assertEqual(image_processor.size			,					{'''height''': 42, '''width''': 42}							)

         # Previous config had dimensions in (width, height) order
         _lowercase:      Any   			=  self.image_processing_class.from_dict(self.image_processor_dict			,					size=(42, 84)							)
         self.assertEqual(image_processor.size			,					{'''height''': 84, '''width''': 42}							)
       def 				lowercase_				(  self							)  ->						Union[str, Any]:





         """simple docstring"""




         pass
       @is_flaky()
       def 				lowercase_				(  self							)  ->						str:





         """simple docstring"""




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

         # Test not batched input
         _lowercase:      Tuple   			=  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
         _lowercase:      List[Any]   			=  image_processing(A_			,					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'''],
             )			,					)
       @is_flaky()
       def 				lowercase_				(  self							)  ->						Any:





         """simple docstring"""




         _lowercase:      str   			=  self.image_processing_class(**self.image_processor_dict							)
         # create random numpy tensors
         _lowercase:      str   			=  prepare_image_inputs(self.image_processor_tester			,					equal_resolution=A_			,					numpify=A_							)
         for image in image_inputs:
           self.assertIsInstance(A_			,					np.ndarray							)

         # Test not batched input
         _lowercase:      Union[str, 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
         _lowercase:      Dict   			=  image_processing(A_			,					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'''],
             )			,					)



       @is_flaky()
       def 				lowercase_				(  self							)  ->						Tuple:





         """simple docstring"""




         _lowercase:      List[Any]   			=  self.image_processing_class(**self.image_processor_dict							)
         # create random PyTorch tensors
         _lowercase:      List[Any]   			=  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
         _lowercase:      Union[str, 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
         _lowercase:      Dict   			=  image_processing(A_			,					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'''],
             )			,					)
