


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, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor



class 							_UpperCamelCase (						unittest.TestCase						):

   '''simple docstring'''







   def __init__(  self  : Tuple       ,  _lowerCamelCase  : int       ,  _lowerCamelCase  : List[str]=1_3       ,  _lowerCamelCase  : Tuple=3       ,  _lowerCamelCase  : Any=2_2_4       ,  _lowerCamelCase  : Optional[int]=3_0       ,  _lowerCamelCase  : Optional[Any]=4_0_0       ,  _lowerCamelCase  : Union[str, Any]=True       ,  _lowerCamelCase  : Optional[Any]=None       ,  _lowerCamelCase  : List[str]=True       ,  _lowerCamelCase  : Optional[int]=[0.5, 0.5, 0.5]       ,  _lowerCamelCase  : Union[str, Any]=[0.5, 0.5, 0.5]       ,  ):






         '''simple docstring'''



         __lowerCamelCase     :      int       						=						size if size is not None else {"""height""": 1_8, """width""": 1_8}
         __lowerCamelCase     :      Optional[int]       						=						parent
         __lowerCamelCase     :      Dict       						=						batch_size
         __lowerCamelCase     :      List[Any]       						=						num_channels
         __lowerCamelCase     :      Tuple       						=						image_size
         __lowerCamelCase     :      int       						=						min_resolution
         __lowerCamelCase     :      List[Any]       						=						max_resolution
         __lowerCamelCase     :      List[str]       						=						do_resize
         __lowerCamelCase     :      str       						=						size
         __lowerCamelCase     :      Optional[Any]       						=						do_normalize
         __lowerCamelCase     :      List[str]       						=						image_mean
         __lowerCamelCase     :      List[str]       						=						image_std


   def   _snake_case    (  self  : Optional[int]							):






         '''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 							_UpperCamelCase (						A,unittest.TestCase						):

   '''simple docstring'''







   a_				:							Tuple    = ViTImageProcessor if is_vision_available() else None

   def   _snake_case    (  self  : Optional[int]							):






         '''simple docstring'''



         __lowerCamelCase     :      int       						=						EfficientFormerImageProcessorTester(self							)

   @property
   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         return self.image_proc_tester.prepare_image_processor_dict()

   def   _snake_case    (  self  : Dict							):






         '''simple docstring'''



         __lowerCamelCase     :      Optional[int]       						=						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   _snake_case    (  self  : List[Any]							):






         '''simple docstring'''



         pass

   def   _snake_case    (  self  : Optional[int]							):






         '''simple docstring'''



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

         # Test not batched input
         __lowerCamelCase     :      List[Any]       						=						image_processor(image_inputs[0]       ,  return_tensors="""pt"""							).pixel_values
         self.assertEqual(
             encoded_images.shape       ,  (
                 1,
                 self.image_proc_tester.num_channels,
                 self.image_proc_tester.size["""height"""],
                 self.image_proc_tester.size["""width"""],
             )       ,  )

         # Test batched
         __lowerCamelCase     :      Tuple       						=						image_processor(_lowerCamelCase       ,  return_tensors="""pt"""							).pixel_values
         self.assertEqual(
             encoded_images.shape       ,  (
                 self.image_proc_tester.batch_size,
                 self.image_proc_tester.num_channels,
                 self.image_proc_tester.size["""height"""],
                 self.image_proc_tester.size["""width"""],
             )       ,  )

   def   _snake_case    (  self  : Union[str, Any]							):






         '''simple docstring'''



         __lowerCamelCase     :      int       						=						self.image_processing_class(**self.image_processor_dict							)
         # create random numpy tensors
         __lowerCamelCase     :      List[str]       						=						prepare_image_inputs(self.image_proc_tester       ,  equal_resolution=_lowerCamelCase       ,  numpify=_lowerCamelCase							)
         for image in image_inputs:
               self.assertIsInstance(_lowerCamelCase       ,  np.ndarray							)

         # Test not batched input
         __lowerCamelCase     :      List[str]       						=						image_processor(image_inputs[0]       ,  return_tensors="""pt"""							).pixel_values
         self.assertEqual(
             encoded_images.shape       ,  (
                 1,
                 self.image_proc_tester.num_channels,
                 self.image_proc_tester.size["""height"""],
                 self.image_proc_tester.size["""width"""],
             )       ,  )

         # Test batched
         __lowerCamelCase     :      Dict       						=						image_processor(_lowerCamelCase       ,  return_tensors="""pt"""							).pixel_values
         self.assertEqual(
             encoded_images.shape       ,  (
                 self.image_proc_tester.batch_size,
                 self.image_proc_tester.num_channels,
                 self.image_proc_tester.size["""height"""],
                 self.image_proc_tester.size["""width"""],
             )       ,  )


   def   _snake_case    (  self  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      Any       						=						self.image_processing_class(**self.image_processor_dict							)
         # create random PyTorch tensors
         __lowerCamelCase     :      Dict       						=						prepare_image_inputs(self.image_proc_tester       ,  equal_resolution=_lowerCamelCase       ,  torchify=_lowerCamelCase							)
         for image in image_inputs:
               self.assertIsInstance(_lowerCamelCase       ,  torch.Tensor							)

         # Test not batched input
         __lowerCamelCase     :      Any       						=						image_processor(image_inputs[0]       ,  return_tensors="""pt"""							).pixel_values
         self.assertEqual(
             encoded_images.shape       ,  (
                 1,
                 self.image_proc_tester.num_channels,
                 self.image_proc_tester.size["""height"""],
                 self.image_proc_tester.size["""width"""],
             )       ,  )

         # Test batched
         __lowerCamelCase     :      List[Any]       						=						image_processor(_lowerCamelCase       ,  return_tensors="""pt"""							).pixel_values
         self.assertEqual(
             encoded_images.shape       ,  (
                 self.image_proc_tester.batch_size,
                 self.image_proc_tester.num_channels,
                 self.image_proc_tester.size["""height"""],
                 self.image_proc_tester.size["""width"""],
             )       ,  )







import re
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin



class 							_UpperCamelCase (						A						):

   '''simple docstring'''







   a_				:							List[Any]    = ["image_processor", "tokenizer"]
   a_				:							Tuple    = "AutoImageProcessor"
   a_				:							Tuple    = "AutoTokenizer"

   def __init__(  self  : Union[str, Any]       ,  _lowerCamelCase  : List[Any]=None       ,  _lowerCamelCase  : Any=None       ,  **_lowerCamelCase  : List[str]							):






         '''simple docstring'''



         __lowerCamelCase     :      Tuple       						=						None
         if "feature_extractor" in kwargs:
               warnings.warn(
                   """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
                   """ instead."""       ,  _lowerCamelCase       ,  )
               __lowerCamelCase     :      List[Any]       						=						kwargs.pop("""feature_extractor"""							)

         __lowerCamelCase     :      Optional[Any]       						=						image_processor if image_processor is not None else feature_extractor
         if image_processor is None:
               raise ValueError("""You need to specify an `image_processor`."""							)
         if tokenizer is None:
               raise ValueError("""You need to specify a `tokenizer`."""							)

         super().__init__(_lowerCamelCase       ,  _lowerCamelCase							)
         __lowerCamelCase     :      List[Any]       						=						self.image_processor
         __lowerCamelCase     :      Any       						=						False

   def __call__(  self  : Union[str, Any]       ,  *_lowerCamelCase  : str       ,  **_lowerCamelCase  : Dict							):






         '''simple docstring'''



         if self._in_target_context_manager:
               return self.current_processor(*_lowerCamelCase       ,  **_lowerCamelCase							)

         __lowerCamelCase     :      List[str]       						=						kwargs.pop("""images"""       ,  _lowerCamelCase							)
         __lowerCamelCase     :      List[str]       						=						kwargs.pop("""text"""       ,  _lowerCamelCase							)
         if len(_lowerCamelCase							) > 0:
               __lowerCamelCase     :      Tuple       						=						args[0]
               __lowerCamelCase     :      List[Any]       						=						args[1:]

         if images is None and text is None:
               raise ValueError("""You need to specify either an `images` or `text` input to process."""							)

         if images is not None:
               __lowerCamelCase     :      Tuple       						=						self.image_processor(_lowerCamelCase       ,  *_lowerCamelCase       ,  **_lowerCamelCase							)
         if text is not None:
               __lowerCamelCase     :      int       						=						self.tokenizer(_lowerCamelCase       ,  **_lowerCamelCase							)

         if text is None:
               return inputs
         elif images is None:
               return encodings
         else:
               __lowerCamelCase     :      Optional[int]       						=						encodings["""input_ids"""]
               return inputs

   def   _snake_case    (  self  : List[Any]       ,  *_lowerCamelCase  : Tuple       ,  **_lowerCamelCase  : Union[str, Any]							):






         '''simple docstring'''



         return self.tokenizer.batch_decode(*_lowerCamelCase       ,  **_lowerCamelCase							)

   def   _snake_case    (  self  : List[str]       ,  *_lowerCamelCase  : Optional[int]       ,  **_lowerCamelCase  : int							):






         '''simple docstring'''



         return self.tokenizer.decode(*_lowerCamelCase       ,  **_lowerCamelCase							)

   @contextmanager
   def   _snake_case    (  self  : Optional[Any]							):






         '''simple docstring'''



         warnings.warn(
             """`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your """
             """labels by using the argument `text` of the regular `__call__` method (either in the same call as """
             """your images inputs, or in a separate call."""							)
         __lowerCamelCase     :      Any       						=						True
         __lowerCamelCase     :      int       						=						self.tokenizer
         yield
         __lowerCamelCase     :      Dict       						=						self.image_processor
         __lowerCamelCase     :      List[Any]       						=						False

   def   _snake_case    (  self  : List[str]       ,  _lowerCamelCase  : str       ,  _lowerCamelCase  : List[str]=False       ,  _lowerCamelCase  : List[Any]=None							):






         '''simple docstring'''



         if added_vocab is None:
               __lowerCamelCase     :      List[str]       						=						self.tokenizer.get_added_vocab()

         __lowerCamelCase     :      List[Any]       						=						{}

         while tokens:
               __lowerCamelCase     :      Dict       						=						re.search(R"""<s_(.*?)>"""       ,  _lowerCamelCase       ,  re.IGNORECASE							)
               if start_token is None:
                     break
               __lowerCamelCase     :      Dict       						=						start_token.group(1							)
               __lowerCamelCase     :      List[str]       						=						re.search(RF"""</s_{key}>"""       ,  _lowerCamelCase       ,  re.IGNORECASE							)
               __lowerCamelCase     :      Optional[int]       						=						start_token.group()
               if end_token is None:
                     __lowerCamelCase     :      int       						=						tokens.replace(_lowerCamelCase       ,  """"""							)
               else:
                     __lowerCamelCase     :      Dict       						=						end_token.group()
                     __lowerCamelCase     :      Optional[Any]       						=						re.escape(_lowerCamelCase							)
                     __lowerCamelCase     :      List[str]       						=						re.escape(_lowerCamelCase							)
                     __lowerCamelCase     :      Any       						=						re.search(F"""{start_token_escaped}(.*?){end_token_escaped}"""       ,  _lowerCamelCase       ,  re.IGNORECASE							)
                     if content is not None:
                           __lowerCamelCase     :      Union[str, Any]       						=						content.group(1							).strip()
                           if r"<s_" in content and r"</s_" in content:  # non-leaf node
                                 __lowerCamelCase     :      Union[str, Any]       						=						self.tokenajson(_lowerCamelCase       ,  is_inner_value=_lowerCamelCase       ,  added_vocab=_lowerCamelCase							)
                                 if value:
                                       if len(_lowerCamelCase							) == 1:
                                             __lowerCamelCase     :      Optional[int]       						=						value[0]
                                       __lowerCamelCase     :      Union[str, Any]       						=						value
                           else:  # leaf nodes
                                 __lowerCamelCase     :      List[Any]       						=						[]
                                 for leaf in content.split(R"""<sep/>"""							):
                                       __lowerCamelCase     :      Optional[Any]       						=						leaf.strip()
                                       if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                                             __lowerCamelCase     :      str       						=						leaf[1:-2]  # for categorical special tokens
                                       output[key].append(_lowerCamelCase							)
                                 if len(output[key]							) == 1:
                                       __lowerCamelCase     :      Tuple       						=						output[key][0]

                     __lowerCamelCase     :      Tuple       						=						tokens[tokens.find(_lowerCamelCase							) + len(_lowerCamelCase							) :].strip()
                     if tokens[:6] == r"<sep/>":  # non-leaf nodes
                           return [output] + self.tokenajson(tokens[6:]       ,  is_inner_value=_lowerCamelCase       ,  added_vocab=_lowerCamelCase							)

         if len(_lowerCamelCase							):
               return [output] if is_inner_value else output
         else:
               return [] if is_inner_value else {"text_sequence": tokens}

   @property
   def   _snake_case    (  self  : Tuple							):






         '''simple docstring'''



         warnings.warn(
             """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""       ,  _lowerCamelCase       ,  )
         return self.image_processor_class


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






         '''simple docstring'''



         warnings.warn(
             """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""       ,  _lowerCamelCase       ,  )
         return self.image_processor



