




import unittest

import numpy as np

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


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import BlipImageProcessor

class   UpperCAmelCase    (      unittest.TestCase ):






   def __init__(						self :							Dict    ,       UpperCamelCase_ :							Optional[int]    ,       UpperCamelCase_ :							Tuple=7    ,       UpperCamelCase_ :							List[Any]=3    ,       UpperCamelCase_ :							Optional[int]=18    ,       UpperCamelCase_ :							Dict=30    ,       UpperCamelCase_ :							Optional[int]=4_00    ,       UpperCamelCase_ :							str=True    ,       UpperCamelCase_ :							Tuple=None    ,       UpperCamelCase_ :							int=True    ,       UpperCamelCase_ :							Tuple=False    ,       UpperCamelCase_ :							Optional[Any]=[0.48_145_466, 0.4_578_275, 0.40_821_073]    ,       UpperCamelCase_ :							Optional[Any]=[0.26_862_954, 0.26_130_258, 0.27_577_711]    ,       UpperCamelCase_ :							Optional[int]=True    ,       )->      List[str]:
     _lowercase:			Union[str, Any]      =     size if size is not None else {'height': 20, 'width': 20}
     _lowercase:			List[Any]      =     parent
     _lowercase:			List[str]      =     batch_size
     _lowercase:			Optional[Any]      =     num_channels
     _lowercase:			Tuple      =     image_size
     _lowercase:			Tuple      =     min_resolution
     _lowercase:			str      =     max_resolution
     _lowercase:			Optional[Any]      =     do_resize
     _lowercase:			Tuple      =     size
     _lowercase:			List[str]      =     do_normalize
     _lowercase:			Tuple      =     image_mean
     _lowercase:			Any      =     image_std
     _lowercase:			List[Any]      =     do_pad
     _lowercase:			Dict      =     do_convert_rgb






   def 			_a    (						self :							Optional[int]  )->      Tuple:
     return {
         "do_resize": self.do_resize,
         "size": self.size,
         "do_normalize": self.do_normalize,
         "image_mean": self.image_mean,
         "image_std": self.image_std,
         "do_convert_rgb": self.do_convert_rgb,
         "do_pad": self.do_pad,
     }






   def 			_a    (						self :							Union[str, Any]    ,       UpperCamelCase_ :							Optional[int]=False    ,       UpperCamelCase_ :							Tuple=False    ,       UpperCamelCase_ :							Dict=False  )->      Union[str, Any]:
     assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

     if equal_resolution:
       _lowercase:			List[Any]      =     []
       for i in range(self.batch_size  ):
         image_inputs.append(
             np.random.randint(
                 2_55    ,       size=(self.num_channels, self.max_resolution, self.max_resolution)    ,       dtype=np.uinta  )  )
     else:
       _lowercase:			Dict      =     []
       for i in range(self.batch_size  ):
         _lowercase  ,       _lowercase:			Optional[int]      =     np.random.choice(np.arange(self.min_resolution    ,       self.max_resolution  )    ,       2  )
         image_inputs.append(np.random.randint(2_55    ,       size=(self.num_channels, width, height)    ,       dtype=np.uinta  )  )

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

     if torchify:
       _lowercase:			Tuple      =     [torch.from_numpy(UpperCamelCase_  ) for x in image_inputs]

     return image_inputs

@require_torch
@require_vision
class   UpperCAmelCase    (      A ,       unittest.TestCase ):
   __SCREAMING_SNAKE_CASE		:				Optional[int]      					=       BlipImageProcessor if is_vision_available() else None






   def 			_a    (						self :							int  )->      List[str]:
     _lowercase:			List[str]      =     BlipImageProcessingTester(self  )






   @property
   def 			_a    (						self :							List[str]  )->      Dict:
     return self.image_processor_tester.prepare_image_processor_dict()






   def 			_a    (						self :							int  )->      Union[str, Any]:
     _lowercase:			Union[str, Any]      =     self.image_processing_class(**self.image_processor_dict  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'do_resize'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'size'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'do_normalize'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'image_mean'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'image_std'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'do_convert_rgb'  )  )






   def 			_a    (						self :							str  )->      Any:
     pass






   def 			_a    (						self :							str  )->      Optional[int]:
     # Initialize image_processor
     _lowercase:			Optional[int]      =     self.image_processing_class(**self.image_processor_dict  )
     # create random PIL images
     _lowercase:			List[Any]      =     self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_  )
     for image in image_inputs:
       self.assertIsInstance(UpperCamelCase_    ,       Image.Image  )

     # Test not batched input
     _lowercase:			Tuple      =     image_processor(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:			str      =     image_processor(UpperCamelCase_    ,       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 			_a    (						self :							Union[str, Any]  )->      Dict:
     # Initialize image_processor
     _lowercase:			Dict      =     self.image_processing_class(**self.image_processor_dict  )
     # create random numpy tensors
     _lowercase:			Union[str, Any]      =     self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_    ,       numpify=UpperCamelCase_  )
     for image in image_inputs:
       self.assertIsInstance(UpperCamelCase_    ,       np.ndarray  )

     # Test not batched input
     _lowercase:			List[Any]      =     image_processor(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_processor(UpperCamelCase_    ,       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 			_a    (						self :							Any  )->      Dict:
     # Initialize image_processor
     _lowercase:			List[Any]      =     self.image_processing_class(**self.image_processor_dict  )
     # create random PyTorch tensors
     _lowercase:			Optional[Any]      =     self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_    ,       torchify=UpperCamelCase_  )
     for image in image_inputs:
       self.assertIsInstance(UpperCamelCase_    ,       torch.Tensor  )

     # Test not batched input
     _lowercase:			Tuple      =     image_processor(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:			Optional[int]      =     image_processor(UpperCamelCase_    ,       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'],
         )    ,       )

@require_torch
@require_vision
class   UpperCAmelCase    (      A ,       unittest.TestCase ):
   __SCREAMING_SNAKE_CASE		:				List[str]      					=       BlipImageProcessor if is_vision_available() else None






   def 			_a    (						self :							int  )->      Optional[Any]:
     _lowercase:			int      =     BlipImageProcessingTester(self    ,       num_channels=4  )
     _lowercase:			Optional[Any]      =     3






   @property
   def 			_a    (						self :							str  )->      Tuple:
     return self.image_processor_tester.prepare_image_processor_dict()






   def 			_a    (						self :							int  )->      Optional[Any]:
     _lowercase:			str      =     self.image_processing_class(**self.image_processor_dict  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'do_resize'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'size'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'do_normalize'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'image_mean'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'image_std'  )  )
     self.assertTrue(hasattr(UpperCamelCase_    ,       'do_convert_rgb'  )  )






   def 			_a    (						self :							Dict  )->      Optional[Any]:
     pass






   def 			_a    (						self :							Any  )->      List[Any]:
     # Initialize image_processor
     _lowercase:			Any      =     self.image_processing_class(**self.image_processor_dict  )
     # create random PIL images
     _lowercase:			List[str]      =     self.image_processor_tester.prepare_inputs(equal_resolution=UpperCamelCase_  )
     for image in image_inputs:
       self.assertIsInstance(UpperCamelCase_    ,       Image.Image  )

     # Test not batched input
     _lowercase:			Optional[int]      =     image_processor(image_inputs[0]    ,       return_tensors='pt'  ).pixel_values
     self.assertEqual(
         encoded_images.shape    ,       (
             1,
             self.expected_encoded_image_num_channels,
             self.image_processor_tester.size['height'],
             self.image_processor_tester.size['width'],
         )    ,       )

     # Test batched
     _lowercase:			List[str]      =     image_processor(UpperCamelCase_    ,       return_tensors='pt'  ).pixel_values
     self.assertEqual(
         encoded_images.shape    ,       (
             self.image_processor_tester.batch_size,
             self.expected_encoded_image_num_channels,
             self.image_processor_tester.size['height'],
             self.image_processor_tester.size['width'],
         )    ,       )






from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available


UpperCAmelCase__    :							List[str]       		=     {
    'configuration_ernie_m': ['ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieMConfig'],
}

try:
   if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase__    :							Any       		=     ['ErnieMTokenizer']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   UpperCAmelCase__    :							Dict       		=     [
       'ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST',
       'ErnieMForMultipleChoice',
       'ErnieMForQuestionAnswering',
       'ErnieMForSequenceClassification',
       'ErnieMForTokenClassification',
       'ErnieMModel',
       'ErnieMPreTrainedModel',
       'ErnieMForInformationExtraction',
   ]


if TYPE_CHECKING:
   from .configuration_ernie_m import ERNIE_M_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieMConfig

   try:
      if not is_sentencepiece_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_ernie_m import ErnieMTokenizer

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_ernie_m import (
          ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST,
          ErnieMForInformationExtraction,
          ErnieMForMultipleChoice,
          ErnieMForQuestionAnswering,
          ErnieMForSequenceClassification,
          ErnieMForTokenClassification,
          ErnieMModel,
          ErnieMPreTrainedModel,
      )


else:
   import sys

   UpperCAmelCase__    :							List[Any]       		=     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
