


'''simple docstring'''






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

  if is_vision_available():
    from transformers import MaskaFormerImageProcessor

if is_vision_available():
  from PIL import Image






class    __snake_case       :







    """simple docstring"""



    def __init__(   self    :  Optional[int]    ,						lowerCamelCase    :  Dict    ,						lowerCamelCase    :  Union[str, Any]=2    ,						lowerCamelCase    :  Optional[Any]=True    ,						lowerCamelCase    :  Union[str, Any]=False    ,						lowerCamelCase    :  Optional[Any]=10    ,						lowerCamelCase    :  Optional[int]=3    ,						lowerCamelCase    :  Tuple=32 * 8    ,						lowerCamelCase    :  Optional[Any]=32 * 8    ,						lowerCamelCase    :  Tuple=4    ,						lowerCamelCase    :  Union[str, Any]=64    ,						)   ->  Tuple:
      lowerCAmelCase_			:      List[str]			=   parent
      lowerCAmelCase_			:      Optional[int]			=   batch_size
      lowerCAmelCase_			:      str			=   is_training
      lowerCAmelCase_			:      Optional[Any]			=   use_auxiliary_loss
      lowerCAmelCase_			:      Optional[Any]			=   num_queries
      lowerCAmelCase_			:      Any			=   num_channels
      lowerCAmelCase_			:      int			=   min_size
      lowerCAmelCase_			:      str			=   max_size
      lowerCAmelCase_			:      Optional[int]			=   num_labels
      lowerCAmelCase_			:      Union[str, Any]			=   hidden_dim
      lowerCAmelCase_			:      List[Any]			=   hidden_dim

    def __lowercase   (   self    :  Any		)   ->  Optional[Any]:
      lowerCAmelCase_			:      List[str]			=   floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]		).to(
          lowerCamelCase		)

      lowerCAmelCase_			:      Optional[Any]			=   torch.ones([self.batch_size, self.min_size, self.max_size]    ,						device=lowerCamelCase		)

      lowerCAmelCase_			:      List[Any]			=   (
          torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]    ,						device=lowerCamelCase		) > 0.5
      ).float()
      lowerCAmelCase_			:      Dict			=   (torch.rand((self.batch_size, self.num_labels)    ,						device=lowerCamelCase		) > 0.5).long()

      lowerCAmelCase_			:      Any			=   self.get_config()
      return config, pixel_values, pixel_mask, mask_labels, class_labels

    def __lowercase   (   self    :  Tuple		)   ->  List[Any]:
      lowerCAmelCase_			:      str			=   MaskaFormerConfig(
          hidden_size=self.hidden_dim    ,						)
      lowerCAmelCase_			:      List[str]			=   self.num_queries
      lowerCAmelCase_			:      Optional[int]			=   self.num_labels

      lowerCAmelCase_			:      Union[str, Any]			=   [1, 1, 1, 1]
      lowerCAmelCase_			:      Optional[int]			=   self.num_channels

      lowerCAmelCase_			:      Optional[int]			=   64
      lowerCAmelCase_			:      Optional[int]			=   1_28
      lowerCAmelCase_			:      str			=   self.hidden_dim
      lowerCAmelCase_			:      str			=   self.hidden_dim
      lowerCAmelCase_			:      Optional[Any]			=   self.hidden_dim
      return config

    def __lowercase   (   self    :  Optional[int]		)   ->  Tuple:
      lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_			:      Any			=   self.prepare_config_and_inputs()
      lowerCAmelCase_			:      Optional[Any]			=   {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
      return config, inputs_dict

    def __lowercase   (   self    :  List[str]    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  List[str]		)   ->  Optional[Any]:
      lowerCAmelCase_			:      Union[str, Any]			=   output.encoder_hidden_states
      lowerCAmelCase_			:      Optional[int]			=   output.pixel_decoder_hidden_states
      lowerCAmelCase_			:      Any			=   output.transformer_decoder_hidden_states

      self.parent.assertTrue(len(lowerCamelCase		)    ,						len(config.backbone_config.depths		)		)
      self.parent.assertTrue(len(lowerCamelCase		)    ,						len(config.backbone_config.depths		)		)
      self.parent.assertTrue(len(lowerCamelCase		)    ,						config.decoder_layers		)

    def __lowercase   (   self    :  Any    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Optional[int]    ,						lowerCamelCase    :  str    ,						lowerCamelCase    :  Any=False		)   ->  str:
      with torch.no_grad():
        lowerCAmelCase_			:      Tuple			=   MaskaFormerModel(config=lowerCamelCase		)
        model.to(lowerCamelCase		)
        model.eval()

        lowerCAmelCase_			:      List[str]			=   model(pixel_values=lowerCamelCase    ,						pixel_mask=lowerCamelCase		)
        lowerCAmelCase_			:      Dict			=   model(lowerCamelCase    ,						output_hidden_states=lowerCamelCase		)

      self.parent.assertEqual(
          output.transformer_decoder_last_hidden_state.shape    ,						(self.batch_size, self.num_queries, self.hidden_dim)    ,						)
      # let's ensure the other two hidden state exists
      self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None		)
      self.parent.assertTrue(output.encoder_last_hidden_state is not None		)

      if output_hidden_states:
        self.check_output_hidden_state(lowerCamelCase    ,						lowerCamelCase		)





    def __lowercase   (   self    :  Tuple    ,						lowerCamelCase    :  Optional[Any]    ,						lowerCamelCase    :  Tuple    ,						lowerCamelCase    :  List[Any]    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  Optional[int]		)   ->  Any:
      lowerCAmelCase_			:      Optional[int]			=   MaskaFormerForUniversalSegmentation(config=lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.eval()

      def comm_check_on_output(lowerCamelCase    :  int		):
        # let's still check that all the required stuff is there
        self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None		)
        self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None		)
        self.parent.assertTrue(result.encoder_last_hidden_state is not None		)
        # okay, now we need to check the logits shape
        # due to the encoder compression, masks have a //4 spatial size
        self.parent.assertEqual(
            result.masks_queries_logits.shape    ,						(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)    ,						)
        # + 1 for null class
        self.parent.assertEqual(
            result.class_queries_logits.shape    ,						(self.batch_size, self.num_queries, self.num_labels + 1)		)

      with torch.no_grad():
        lowerCAmelCase_			:      Tuple			=   model(pixel_values=lowerCamelCase    ,						pixel_mask=lowerCamelCase		)
        lowerCAmelCase_			:      Dict			=   model(lowerCamelCase		)

        comm_check_on_output(lowerCamelCase		)

        lowerCAmelCase_			:      Optional[Any]			=   model(
            pixel_values=lowerCamelCase    ,						pixel_mask=lowerCamelCase    ,						mask_labels=lowerCamelCase    ,						class_labels=lowerCamelCase		)

      comm_check_on_output(lowerCamelCase		)

      self.parent.assertTrue(result.loss is not None		)
      self.parent.assertEqual(result.loss.shape    ,						torch.Size([1]		)		)







@require_torch
class    __snake_case       (   _SCREAMING_SNAKE_CASE	,_SCREAMING_SNAKE_CASE	,unittest.TestCase):







    """simple docstring"""



    lowercase    =					(MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
    lowercase    =					{'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

    lowercase    =					False
    lowercase    =					False
    lowercase    =					False
    lowercase    =					False

    def __lowercase   (   self    :  Any		)   ->  str:
      lowerCAmelCase_			:      Optional[Any]			=   MaskaFormerModelTester(self		)
      lowerCAmelCase_			:      Union[str, Any]			=   ConfigTester(self    ,						config_class=lowerCamelCase    ,						has_text_modality=lowerCamelCase		)

    def __lowercase   (   self    :  Dict		)   ->  Any:
      self.config_tester.run_common_tests()

    def __lowercase   (   self    :  Optional[int]		)   ->  Tuple:
      lowerCAmelCase_,							lowerCAmelCase_			:      Dict			=   self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskaformer_model(lowerCamelCase    ,						**lowerCamelCase    ,						output_hidden_states=lowerCamelCase		)

    def __lowercase   (   self    :  List[Any]		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      Any			=   self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*lowerCamelCase		)

    @unittest.skip(reason="""Mask2Former does not use inputs_embeds"""		)
    def __lowercase   (   self    :  List[Any]		)   ->  Union[str, Any]:
      pass

    @unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""		)
    def __lowercase   (   self    :  Any		)   ->  List[Any]:
      pass

    @unittest.skip(reason="""Mask2Former is not a generative model"""		)
    def __lowercase   (   self    :  Union[str, Any]		)   ->  List[str]:
      pass

    @unittest.skip(reason="""Mask2Former does not use token embeddings"""		)
    def __lowercase   (   self    :  Union[str, Any]		)   ->  Tuple:
      pass

    @require_torch_multi_gpu
    @unittest.skip(
        reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""		)
    def __lowercase   (   self    :  Dict		)   ->  List[Any]:
      pass

    @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""		)
    def __lowercase   (   self    :  Any		)   ->  List[str]:
      pass

    def __lowercase   (   self    :  Tuple		)   ->  List[Any]:
      lowerCAmelCase_,							lowerCAmelCase_			:      Union[str, Any]			=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCAmelCase_			:      Optional[Any]			=   model_class(lowerCamelCase		)
        lowerCAmelCase_			:      int			=   inspect.signature(model.forward		)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowerCAmelCase_			:      Any			=   [*signature.parameters.keys()]

        lowerCAmelCase_			:      Tuple			=   ["""pixel_values"""]
        self.assertListEqual(arg_names[:1]    ,						lowerCamelCase		)

    @slow
    def __lowercase   (   self    :  str		)   ->  Optional[Any]:
      for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
        lowerCAmelCase_			:      Optional[Any]			=   MaskaFormerModel.from_pretrained(lowerCamelCase		)
        self.assertIsNotNone(lowerCamelCase		)

    def __lowercase   (   self    :  Any		)   ->  Tuple:
      lowerCAmelCase_			:      Any			=   (self.model_tester.min_size,) * 2
      lowerCAmelCase_			:      str			=   {
          """pixel_values""": torch.randn((2, 3, *size)    ,						device=lowerCamelCase		),
          """mask_labels""": torch.randn((2, 10, *size)    ,						device=lowerCamelCase		),
          """class_labels""": torch.zeros(2    ,						10    ,						device=lowerCamelCase		).long(),
      }
      lowerCAmelCase_			:      Any			=   self.model_tester.get_config()

      lowerCAmelCase_			:      int			=   MaskaFormerForUniversalSegmentation(lowerCamelCase		).to(lowerCamelCase		)
      lowerCAmelCase_			:      Optional[Any]			=   model(**lowerCamelCase		)
      self.assertTrue(outputs.loss is not None		)

    def __lowercase   (   self    :  Optional[Any]		)   ->  str:
      lowerCAmelCase_,							lowerCAmelCase_			:      Tuple			=   self.model_tester.prepare_config_and_inputs_for_common()
      self.model_tester.create_and_check_maskaformer_model(lowerCamelCase    ,						**lowerCamelCase    ,						output_hidden_states=lowerCamelCase		)

    def __lowercase   (   self    :  Optional[int]		)   ->  Optional[Any]:
      lowerCAmelCase_,							lowerCAmelCase_			:      List[Any]			=   self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        lowerCAmelCase_			:      List[Any]			=   model_class(lowerCamelCase		).to(lowerCamelCase		)
        lowerCAmelCase_			:      List[str]			=   model(**lowerCamelCase    ,						output_attentions=lowerCamelCase		)
        self.assertTrue(outputs.attentions is not None		)

    def __lowercase   (   self    :  Dict		)   ->  Union[str, Any]:
      if not self.model_tester.is_training:
        return

      lowerCAmelCase_			:      List[Any]			=   self.all_model_classes[1]
      lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_			:      Tuple			=   self.model_tester.prepare_config_and_inputs()

      lowerCAmelCase_			:      int			=   model_class(lowerCamelCase		)
      model.to(lowerCamelCase		)
      model.train()

      lowerCAmelCase_			:      int			=   model(lowerCamelCase    ,						mask_labels=lowerCamelCase    ,						class_labels=lowerCamelCase		).loss
      loss.backward()





    def __lowercase   (   self    :  Optional[int]		)   ->  str:
      lowerCAmelCase_			:      Optional[int]			=   self.all_model_classes[1]
      lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_,							lowerCAmelCase_			:      Tuple			=   self.model_tester.prepare_config_and_inputs()
      lowerCAmelCase_			:      int			=   True
      lowerCAmelCase_			:      Optional[Any]			=   True

      lowerCAmelCase_			:      Tuple			=   model_class(lowerCamelCase		).to(lowerCamelCase		)
      model.train()

      lowerCAmelCase_			:      Optional[Any]			=   model(lowerCamelCase    ,						mask_labels=lowerCamelCase    ,						class_labels=lowerCamelCase		)

      lowerCAmelCase_			:      Any			=   outputs.encoder_hidden_states[0]
      encoder_hidden_states.retain_grad()

      lowerCAmelCase_			:      Tuple			=   outputs.pixel_decoder_hidden_states[0]
      pixel_decoder_hidden_states.retain_grad()

      lowerCAmelCase_			:      Dict			=   outputs.transformer_decoder_hidden_states[0]
      transformer_decoder_hidden_states.retain_grad()

      lowerCAmelCase_			:      List[str]			=   outputs.attentions[0]
      attentions.retain_grad()

      outputs.loss.backward(retain_graph=lowerCamelCase		)

      self.assertIsNotNone(encoder_hidden_states.grad		)
      self.assertIsNotNone(pixel_decoder_hidden_states.grad		)
      self.assertIsNotNone(transformer_decoder_hidden_states.grad		)
      self.assertIsNotNone(attentions.grad		)







__A					:  Optional[Any]											=      1E-4







def 				UpperCamelCase_			(    ):
  '''simple docstring'''





  lowerCAmelCase_			:      Optional[Any]			=   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
  return image






@require_vision
@slow
class    __snake_case       (   unittest.TestCase):







    """simple docstring"""



    @cached_property
    def __lowercase   (   self    :  List[Any]		)   ->  Union[str, Any]:
      return "facebook/mask2former-swin-small-coco-instance"

    @cached_property
    def __lowercase   (   self    :  Any		)   ->  Dict:
      return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints		) if is_vision_available() else None

    def __lowercase   (   self    :  Dict		)   ->  int:
      lowerCAmelCase_			:      Union[str, Any]			=   MaskaFormerModel.from_pretrained(self.model_checkpoints		).to(lowerCamelCase		)
      lowerCAmelCase_			:      Any			=   self.default_image_processor
      lowerCAmelCase_			:      Union[str, Any]			=   prepare_img()
      lowerCAmelCase_			:      Optional[Any]			=   image_processor(lowerCamelCase    ,						return_tensors="""pt"""		).to(lowerCamelCase		)
      lowerCAmelCase_			:      str			=   inputs["""pixel_values"""].shape
      # check size is divisible by 32
      self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0		)
      # check size
      self.assertEqual(lowerCamelCase    ,						(1, 3, 3_84, 3_84)		)

      with torch.no_grad():
        lowerCAmelCase_			:      Any			=   model(**lowerCamelCase		)

      lowerCAmelCase_			:      str			=   torch.tensor(
          [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]]		).to(lowerCamelCase		)
      self.assertTrue(
          torch.allclose(
              outputs.encoder_last_hidden_state[0, 0, :3, :3]    ,						lowerCamelCase    ,						atol=lowerCamelCase		)		)

      lowerCAmelCase_			:      List[Any]			=   torch.tensor(
          [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]]		).to(lowerCamelCase		)
      self.assertTrue(
          torch.allclose(
              outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]    ,						lowerCamelCase    ,						atol=lowerCamelCase		)		)

      lowerCAmelCase_			:      Optional[int]			=   torch.tensor(
          [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]]		).to(lowerCamelCase		)
      self.assertTrue(
          torch.allclose(
              outputs.transformer_decoder_last_hidden_state[0, :3, :3]    ,						lowerCamelCase    ,						atol=lowerCamelCase		)		)

    def __lowercase   (   self    :  Optional[int]		)   ->  Union[str, Any]:
      lowerCAmelCase_			:      int			=   MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints		).to(lowerCamelCase		).eval()
      lowerCAmelCase_			:      str			=   self.default_image_processor
      lowerCAmelCase_			:      Tuple			=   prepare_img()
      lowerCAmelCase_			:      Optional[Any]			=   image_processor(lowerCamelCase    ,						return_tensors="""pt"""		).to(lowerCamelCase		)
      lowerCAmelCase_			:      Any			=   inputs["""pixel_values"""].shape
      # check size is divisible by 32
      self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0		)
      # check size
      self.assertEqual(lowerCamelCase    ,						(1, 3, 3_84, 3_84)		)

      with torch.no_grad():
        lowerCAmelCase_			:      Optional[int]			=   model(**lowerCamelCase		)
      # masks_queries_logits
      lowerCAmelCase_			:      Union[str, Any]			=   outputs.masks_queries_logits
      self.assertEqual(
          masks_queries_logits.shape    ,						(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)		)
      lowerCAmelCase_			:      str			=   [
          [-8.7_839, -9.0_056, -8.8_121],
          [-7.4_104, -7.0_313, -6.5_401],
          [-6.6_105, -6.3_427, -6.4_675],
      ]
      lowerCAmelCase_			:      int			=   torch.tensor(lowerCamelCase		).to(lowerCamelCase		)
      self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]    ,						lowerCamelCase    ,						atol=lowerCamelCase		)		)
      # class_queries_logits
      lowerCAmelCase_			:      int			=   outputs.class_queries_logits
      self.assertEqual(class_queries_logits.shape    ,						(1, model.config.num_queries, model.config.num_labels + 1)		)
      lowerCAmelCase_			:      Optional[Any]			=   torch.tensor(
          [
              [1.8_324, -8.0_835, -4.1_922],
              [0.8_450, -9.0_050, -3.6_053],
              [0.3_045, -7.7_293, -3.0_275],
          ]		).to(lowerCamelCase		)
      self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]    ,						lowerCamelCase    ,						atol=lowerCamelCase		)		)





    def __lowercase   (   self    :  int		)   ->  int:
      lowerCAmelCase_			:      Dict			=   MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints		).to(lowerCamelCase		).eval()
      lowerCAmelCase_			:      Optional[int]			=   self.default_image_processor

      lowerCAmelCase_			:      Optional[Any]			=   image_processor(
          [np.zeros((3, 8_00, 13_33)		), np.zeros((3, 8_00, 13_33)		)]    ,						segmentation_maps=[np.zeros((3_84, 3_84)		).astype(np.floataa		), np.zeros((3_84, 3_84)		).astype(np.floataa		)]    ,						return_tensors="""pt"""    ,						)

      lowerCAmelCase_			:      Union[str, Any]			=   inputs["""pixel_values"""].to(lowerCamelCase		)
      lowerCAmelCase_			:      Any			=   [el.to(lowerCamelCase		) for el in inputs["""mask_labels"""]]
      lowerCAmelCase_			:      Union[str, Any]			=   [el.to(lowerCamelCase		) for el in inputs["""class_labels"""]]

      with torch.no_grad():
        lowerCAmelCase_			:      int			=   model(**lowerCamelCase		)

      self.assertTrue(outputs.loss is not None		)







'''simple docstring'''






import re
import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin






class    __snake_case       (   _SCREAMING_SNAKE_CASE):







    """simple docstring"""



    lowercase    =					['image_processor', 'tokenizer']
    lowercase    =					'AutoImageProcessor'
    lowercase    =					'AutoTokenizer'

    def __init__(   self    :  int    ,						lowerCamelCase    :  List[str]=None    ,						lowerCamelCase    :  Union[str, Any]=None    ,						**lowerCamelCase    :  str		)   ->  Tuple:
      lowerCAmelCase_			:      str			=   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_			:      Tuple			=   kwargs.pop("""feature_extractor"""		)

      lowerCAmelCase_			:      Tuple			=   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_			:      Optional[int]			=   self.image_processor
      lowerCAmelCase_			:      Any			=   False

    def __call__(   self    :  List[Any]    ,						*lowerCamelCase    :  str    ,						**lowerCamelCase    :  Tuple		)   ->  Union[str, Any]:
      # For backward compatibility
      if self._in_target_context_manager:
        return self.current_processor(*lowerCamelCase    ,						**lowerCamelCase		)

      lowerCAmelCase_			:      Any			=   kwargs.pop("""images"""    ,						lowerCamelCase		)
      lowerCAmelCase_			:      Dict			=   kwargs.pop("""text"""    ,						lowerCamelCase		)
      if len(lowerCamelCase		) > 0:
        lowerCAmelCase_			:      str			=   args[0]
        lowerCAmelCase_			:      Dict			=   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_			:      Any			=   self.image_processor(lowerCamelCase    ,						*lowerCamelCase    ,						**lowerCamelCase		)
      if text is not None:
        lowerCAmelCase_			:      str			=   self.tokenizer(lowerCamelCase    ,						**lowerCamelCase		)

      if text is None:
        return inputs
      elif images is None:
        return encodings
      else:
        lowerCAmelCase_			:      Dict			=   encodings["""input_ids"""]
        return inputs

    def __lowercase   (   self    :  str    ,						*lowerCamelCase    :  Union[str, Any]    ,						**lowerCamelCase    :  Union[str, Any]		)   ->  List[str]:
      return self.tokenizer.batch_decode(*lowerCamelCase    ,						**lowerCamelCase		)

    def __lowercase   (   self    :  List[Any]    ,						*lowerCamelCase    :  Any    ,						**lowerCamelCase    :  Union[str, Any]		)   ->  List[str]:
      return self.tokenizer.decode(*lowerCamelCase    ,						**lowerCamelCase		)

    @contextmanager
    def __lowercase   (   self    :  str		)   ->  Union[str, Any]:
      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_			:      List[str]			=   True
      lowerCAmelCase_			:      Optional[Any]			=   self.tokenizer
      yield
      lowerCAmelCase_			:      List[Any]			=   self.image_processor
      lowerCAmelCase_			:      List[str]			=   False

    def __lowercase   (   self    :  Dict    ,						lowerCamelCase    :  List[str]    ,						lowerCamelCase    :  str=False    ,						lowerCamelCase    :  List[Any]=None		)   ->  Optional[int]:
      if added_vocab is None:
        lowerCAmelCase_			:      str			=   self.tokenizer.get_added_vocab()

      lowerCAmelCase_			:      Union[str, Any]			=   {}

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

          lowerCAmelCase_			:      List[Any]			=   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 __lowercase   (   self    :  Dict		)   ->  int:
      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 __lowercase   (   self    :  Dict		)   ->  Optional[Any]:
      warnings.warn(
          """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""    ,						lowerCamelCase    ,						)
      return self.image_processor



