import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available


if is_torch_available():
   import numpy as np
   import torch

if is_vision_available():
   from PIL import Image


def 							lowerCAmelCase__    (       a__  ,			a__=False  ,			a__=False  ,			a__=False      )	->Optional[Any]:




  '''simple docstring'''

  assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

  _UpperCamelCase				=  []
  for i in range(image_processor_tester.batch_size      ):
    if equal_resolution:
      _UpperCamelCase				=  _UpperCamelCase				=  image_processor_tester.max_resolution
    else:
      # To avoid getting image width/height 0
      _UpperCamelCase				=  image_processor_tester.min_resolution
      if getattr(a__  ,			"size_divisor"  ,			a__      ):
        # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
        _UpperCamelCase				=  max(image_processor_tester.size_divisor  ,			a__      )
      _UpperCamelCase	,		_UpperCamelCase				=  np.random.choice(np.arange(a__  ,			image_processor_tester.max_resolution      )  ,			2      )
    image_inputs.append(
        np.random.randint(255  ,			size=(image_processor_tester.num_channels, width, height)  ,			dtype=np.uinta      )      )

  if not numpify and not torchify:
    # PIL expects the channel dimension as last dimension
    _UpperCamelCase				=  [Image.fromarray(np.moveaxis(a__  ,			0  ,			-1      )      ) for image in image_inputs]

  if torchify:
    _UpperCamelCase				=  [torch.from_numpy(a__      ) for image in image_inputs]

  return image_inputs


def 							lowerCAmelCase__    (       a__  ,			a__=10  ,			a__=10  ,			a__=False  ,			a__=False      )	->Optional[int]:




  '''simple docstring'''

  _UpperCamelCase				=  []
  for i in range(image_processor_tester.num_frames      ):
    video.append(np.random.randint(255  ,			size=(image_processor_tester.num_channels, width, height)  ,			dtype=np.uinta      )      )

  if not numpify and not torchify:
    # PIL expects the channel dimension as last dimension
    _UpperCamelCase				=  [Image.fromarray(np.moveaxis(a__  ,			0  ,			-1      )      ) for frame in video]

  if torchify:
    _UpperCamelCase				=  [torch.from_numpy(a__      ) for frame in video]

  return video


def 							lowerCAmelCase__    (       a__  ,			a__=False  ,			a__=False  ,			a__=False      )	->Dict:




  '''simple docstring'''

  assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

  _UpperCamelCase				=  []
  for i in range(image_processor_tester.batch_size      ):
    if equal_resolution:
      _UpperCamelCase				=  _UpperCamelCase				=  image_processor_tester.max_resolution
    else:
      _UpperCamelCase	,		_UpperCamelCase				=  np.random.choice(
          np.arange(image_processor_tester.min_resolution  ,			image_processor_tester.max_resolution      )  ,			2      )
      _UpperCamelCase				=  prepare_video(
          image_processor_tester=a__  ,			width=a__  ,			height=a__  ,			numpify=a__  ,			torchify=a__  ,			)
    video_inputs.append(a__      )

  return video_inputs







class  _UpperCAmelCase       :



 '''simple docstring'''




 __A           = None







 def 						__UpperCAmelCase							(						self							:					Dict)		->     Tuple:


   """simple docstring"""







   _UpperCamelCase				=  self.image_processing_class(**self.image_processor_dict)
   _UpperCamelCase				=  json.loads(image_processor.to_json_string())
   for key, value in self.image_processor_dict.items():
     self.assertEqual(obj[key]				,      lowercase_)







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


   """simple docstring"""







   _UpperCamelCase				=  self.image_processing_class(**self.image_processor_dict)

   with tempfile.TemporaryDirectory() as tmpdirname:
     _UpperCamelCase				=  os.path.join(lowercase_				,      "image_processor.json")
     image_processor_first.to_json_file(lowercase_)
     _UpperCamelCase				=  self.image_processing_class.from_json_file(lowercase_)

   self.assertEqual(image_processor_second.to_dict()				,      image_processor_first.to_dict())







 def 						__UpperCAmelCase							(						self							:					Any)		->     Tuple:


   """simple docstring"""







   _UpperCamelCase				=  self.image_processing_class(**self.image_processor_dict)

   with tempfile.TemporaryDirectory() as tmpdirname:
     _UpperCamelCase				=  image_processor_first.save_pretrained(lowercase_)[0]
     check_json_file_has_correct_format(lowercase_)
     _UpperCamelCase				=  self.image_processing_class.from_pretrained(lowercase_)

   self.assertEqual(image_processor_second.to_dict()				,      image_processor_first.to_dict())







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


   """simple docstring"""







   _UpperCamelCase				=  self.image_processing_class()
   self.assertIsNotNone(lowercase_)







 @require_torch
 @require_vision
 def 						__UpperCAmelCase							(						self							:					str)		->     List[str]:


   """simple docstring"""







   if self.test_cast_dtype is not None:
     # Initialize image_processor
     _UpperCamelCase				=  self.image_processing_class(**self.image_processor_dict)

     # create random PyTorch tensors
     _UpperCamelCase				=  prepare_image_inputs(self.image_processor_tester				,      equal_resolution=lowercase_				,      torchify=lowercase_)

     _UpperCamelCase				=  image_processor(lowercase_				,      return_tensors="pt")
     # for layoutLM compatiblity
     self.assertEqual(encoding.pixel_values.device				,      torch.device("cpu"))
     self.assertEqual(encoding.pixel_values.dtype				,      torch.floataa)

     _UpperCamelCase				=  image_processor(lowercase_				,      return_tensors="pt").to(torch.floataa)
     self.assertEqual(encoding.pixel_values.device				,      torch.device("cpu"))
     self.assertEqual(encoding.pixel_values.dtype				,      torch.floataa)

     _UpperCamelCase				=  image_processor(lowercase_				,      return_tensors="pt").to("cpu"				,      torch.bfloataa)
     self.assertEqual(encoding.pixel_values.device				,      torch.device("cpu"))
     self.assertEqual(encoding.pixel_values.dtype				,      torch.bfloataa)

     with self.assertRaises(lowercase_):
       _UpperCamelCase				=  image_processor(lowercase_				,      return_tensors="pt").to(torch.bfloataa				,      "cpu")

     # Try with text + image feature
     _UpperCamelCase				=  image_processor(lowercase_				,      return_tensors="pt")
     encoding.update({"input_ids": torch.LongTensor([[1, 2, 3], [4, 5, 6]])})
     _UpperCamelCase				=  encoding.to(torch.floataa)

     self.assertEqual(encoding.pixel_values.device				,      torch.device("cpu"))
     self.assertEqual(encoding.pixel_values.dtype				,      torch.floataa)
     self.assertEqual(encoding.input_ids.dtype				,      torch.long)





from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase__   = logging.get_logger(__name__)

lowerCamelCase__   = {
    '''nghuyong/ernie-1.0-base-zh''': '''https://huggingface.co/nghuyong/ernie-1.0-base-zh/resolve/main/config.json''',
    '''nghuyong/ernie-2.0-base-en''': '''https://huggingface.co/nghuyong/ernie-2.0-base-en/resolve/main/config.json''',
    '''nghuyong/ernie-2.0-large-en''': '''https://huggingface.co/nghuyong/ernie-2.0-large-en/resolve/main/config.json''',
    '''nghuyong/ernie-3.0-base-zh''': '''https://huggingface.co/nghuyong/ernie-3.0-base-zh/resolve/main/config.json''',
    '''nghuyong/ernie-3.0-medium-zh''': '''https://huggingface.co/nghuyong/ernie-3.0-medium-zh/resolve/main/config.json''',
    '''nghuyong/ernie-3.0-mini-zh''': '''https://huggingface.co/nghuyong/ernie-3.0-mini-zh/resolve/main/config.json''',
    '''nghuyong/ernie-3.0-micro-zh''': '''https://huggingface.co/nghuyong/ernie-3.0-micro-zh/resolve/main/config.json''',
    '''nghuyong/ernie-3.0-nano-zh''': '''https://huggingface.co/nghuyong/ernie-3.0-nano-zh/resolve/main/config.json''',
    '''nghuyong/ernie-gram-zh''': '''https://huggingface.co/nghuyong/ernie-gram-zh/resolve/main/config.json''',
    '''nghuyong/ernie-health-zh''': '''https://huggingface.co/nghuyong/ernie-health-zh/resolve/main/config.json''',
}




class  _UpperCAmelCase       (			lowerCAmelCase   ):



 '''simple docstring'''




 __A           = '''ernie'''







 def __init__(						self							:					Dict				,      lowercase_							:					List[Any]=30522				,      lowercase_							:					Optional[int]=768				,      lowercase_							:					Tuple=12				,      lowercase_							:					Optional[int]=12				,      lowercase_							:					Any=3072				,      lowercase_							:					int="gelu"				,      lowercase_							:					List[Any]=0.1				,      lowercase_							:					Any=0.1				,      lowercase_							:					str=512				,      lowercase_							:					Any=2				,      lowercase_							:					Any=3				,      lowercase_							:					List[Any]=False				,      lowercase_							:					List[Any]=0.02				,      lowercase_							:					str=1e-1_2				,      lowercase_							:					int=0				,      lowercase_							:					str="absolute"				,      lowercase_							:					Dict=True				,      lowercase_							:					List[str]=None				,      **lowercase_							:					Dict				,      )		->     Union[str, Any]:


   """simple docstring"""







   super().__init__(pad_token_id=lowercase_				,      **lowercase_)

   _UpperCamelCase				=  vocab_size
   _UpperCamelCase				=  hidden_size
   _UpperCamelCase				=  num_hidden_layers
   _UpperCamelCase				=  num_attention_heads
   _UpperCamelCase				=  hidden_act
   _UpperCamelCase				=  intermediate_size
   _UpperCamelCase				=  hidden_dropout_prob
   _UpperCamelCase				=  attention_probs_dropout_prob
   _UpperCamelCase				=  max_position_embeddings
   _UpperCamelCase				=  type_vocab_size
   _UpperCamelCase				=  task_type_vocab_size
   _UpperCamelCase				=  use_task_id
   _UpperCamelCase				=  initializer_range
   _UpperCamelCase				=  layer_norm_eps
   _UpperCamelCase				=  position_embedding_type
   _UpperCamelCase				=  use_cache
   _UpperCamelCase				=  classifier_dropout




class  _UpperCAmelCase       (			lowerCAmelCase   ):



 '''simple docstring'''




 @property
 def 						__UpperCAmelCase							(						self							:					Optional[int])		->     Mapping[str, Mapping[int, str]]:


   """simple docstring"""







   if self.task == "multiple-choice":
     _UpperCamelCase				=  {0: "batch", 1: "choice", 2: "sequence"}
   else:
     _UpperCamelCase				=  {0: "batch", 1: "sequence"}
   return OrderedDict(
       [
           ("input_ids", dynamic_axis),
           ("attention_mask", dynamic_axis),
           ("token_type_ids", dynamic_axis),
           ("task_type_ids", dynamic_axis),
       ])




