

'''simple docstring'''
import argparse
import os
from functools import reduce

import fairseq
import torch
from datasets import load_dataset

from transformers import WavaVecaProcessor, logging
from transformers.models.dataavec.configuration_dataavec_audio import DataaVecAudioConfig

# Copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_audio.py
from transformers.models.dataavec.dataavec_audio import DataaVecAudioModel as Dummy  # noqa: F401
from transformers.models.dataavec.modeling_dataavec_audio import DataaVecAudioForCTC, DataaVecAudioModel


logging.set_verbosity_info()
_snake_case     						=						logging.get_logger(__name__)

_snake_case     						=						{
    'post_extract_proj': 'feature_projection.projection',
    'models.0.layer_norm': 'feature_projection.layer_norm',
    'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
    'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
    'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
    'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
    'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
    'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
    'fc2': 'encoder.layers.*.feed_forward.output_dense',
    'final_layer_norm': 'encoder.layers.*.final_layer_norm',
    'encoder.layer_norm': 'encoder.layer_norm',
    'w2v_model.layer_norm': 'feature_projection.layer_norm',
    'w2v_encoder.proj': 'lm_head',
    'mask_emb': 'masked_spec_embed',
}
_snake_case     						=						[
    'lm_head',
]







def       _A	(			snake_case	,       snake_case	,       snake_case	,       snake_case	,       snake_case  )    ->			str:
   for attribute in key.split("."  ):
      _lowercase    :   Union[str, Any]      =     getattr(snake_case	,       snake_case  )

   if weight_type is not None:
      _lowercase    :   str      =     getattr(snake_case	,       snake_case  ).shape
   else:
      _lowercase    :   Union[str, Any]      =     hf_pointer.shape

   if hf_shape != value.shape:
      raise ValueError(
          F'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
          F''' {value.shape} for {full_name}'''  )

   if weight_type == "weight":
      _lowercase    :   Optional[int]      =     value
   elif weight_type == "weight_g":
      _lowercase    :   Optional[Any]      =     value
   elif weight_type == "weight_v":
      _lowercase    :   Union[str, Any]      =     value
   elif weight_type == "bias":
      _lowercase    :   Union[str, Any]      =     value
   else:
      _lowercase    :   Dict      =     value

   logger.info(F'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.'''  )







def       _A	(			snake_case	,       snake_case	,       snake_case  )    ->			Optional[Any]:
   _lowercase    :   str      =     []
   _lowercase    :   Tuple      =     fairseq_model.state_dict()

   if not is_headless:
      _lowercase    :   List[Any]      =     hf_model.dataavec_audio.feature_extractor
      _lowercase    :   int      =     hf_model.dataavec_audio.encoder.pos_conv_embed

   else:
      _lowercase    :   Union[str, Any]      =     hf_model.feature_extractor
      _lowercase    :   Union[str, Any]      =     hf_model.encoder.pos_conv_embed

   for name, value in fairseq_dict.items():
      _lowercase    :   Dict      =     False
      if "conv_layers" in name:
         load_conv_layer(
             snake_case	,       snake_case	,       snake_case	,       snake_case	,       )
         _lowercase    :   Optional[Any]      =     True
      elif "pos_conv" in name:
         load_pos_conv_layer(
             snake_case	,       snake_case	,       snake_case	,       snake_case	,       )
         _lowercase    :   Optional[Any]      =     True
      else:
         for key, mapped_key in MAPPING.items():
            if not is_headless:
               _lowercase    :   List[Any]      =     "data2vec_audio." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
            if key in name or key.split("w2v_model."  )[-1] == name.split("."  )[0]:
               _lowercase    :   Optional[Any]      =     True
               if "*" in mapped_key:
                  _lowercase    :   Tuple      =     name.split(snake_case  )[0].split("."  )[-2]
                  _lowercase    :   Tuple      =     mapped_key.replace("*"	,       snake_case  )
               if "weight_g" in name:
                  _lowercase    :   Tuple      =     "weight_g"
               elif "weight_v" in name:
                  _lowercase    :   str      =     "weight_v"
               elif "bias" in name:
                  _lowercase    :   Dict      =     "bias"
               elif "weight" in name:
                  # TODO: don't match quantizer.weight_proj
                  _lowercase    :   Tuple      =     "weight"
               else:
                  _lowercase    :   Any      =     None
               set_recursively(snake_case	,       snake_case	,       snake_case	,       snake_case	,       snake_case  )
            continue
      if not is_used:
         unused_weights.append(snake_case  )

   logger.warning(F'''Unused weights: {unused_weights}'''  )







def       _A	(			snake_case	,       snake_case  )    ->			Optional[Any]:
   _lowercase    :   Optional[int]      =     path.split("."  )
   return reduce(snake_case	,       snake_case	,       snake_case  )







def       _A	(			snake_case	,       snake_case	,       snake_case	,       snake_case  )    ->			Optional[int]:
   _lowercase    :   Dict      =     access_by_string(snake_case	,       snake_case  )
   _lowercase    :   Dict      =     hf_weight.data

   if fsq_value.shape != hf_value.shape:
      raise ValueError(F'''{full_name} has size {fsq_value.shape}, but {hf_value.shape} was found.'''  )
   _lowercase    :   Dict      =     fsq_value
   logger.info(F'''{full_name} was correctly initialized from {hf_weight_path}.'''  )







def       _A	(			snake_case	,       snake_case	,       snake_case	,       snake_case  )    ->			Union[str, Any]:
   _lowercase    :   List[Any]      =     full_name.split("conv_layers."  )[-1]
   _lowercase    :   List[str]      =     name.split("."  )
   _lowercase    :   int      =     int(items[0]  )
   _lowercase    :   Optional[Any]      =     int(items[1]  )

   _lowercase    :   List[Any]      =     name.split("."  )[-1]
   if type_id == 0:
      _lowercase    :   int      =     "conv"
   elif type_id == 2:
      _lowercase    :   Union[str, Any]      =     "layer_norm"
   else:
      unused_weights.append(snake_case  )
      return

   set_weights(snake_case	,       snake_case	,       snake_case	,       F'''conv_layers.{layer_id}.{layer_type}.{weight_type}'''  )







def       _A	(			snake_case	,       snake_case	,       snake_case	,       snake_case  )    ->			Optional[Any]:
   _lowercase    :   Tuple      =     full_name.split("pos_conv."  )[-1]
   _lowercase    :   str      =     name.split("."  )
   _lowercase    :   int      =     int(items[0]  )
   _lowercase    :   List[Any]      =     int(items[1]  )

   _lowercase    :   int      =     name.split("."  )[-1]
   if type_id != 0:
      unused_weights.append(snake_case  )
      return
   else:
      _lowercase    :   str      =     "conv"

   set_weights(snake_case	,       snake_case	,       snake_case	,       F'''layers.{layer_id}.{layer_type}.{weight_type}'''  )







@torch.no_grad()
def       _A	(			snake_case	,       snake_case	,       snake_case=None	,       snake_case=None	,       snake_case=True  )    ->			Dict:
   if config_path is not None:
      _lowercase    :   Dict      =     DataaVecAudioConfig.from_pretrained(snake_case  )
   else:
      _lowercase    :   Tuple      =     DataaVecAudioConfig()

   if not is_finetuned:
      # Modify final_proj layer name
      _lowercase    :   Dict      =     DataaVecAudioModel(snake_case  )
      _lowercase    :   List[Any]      =     os.path.dirname(snake_case  )

      _lowercase    :   Optional[Any]      =     torch.load(snake_case  )
      _lowercase    :   str      =     state_dict["model"].pop("final_proj.0.weight"  )
      _lowercase    :   Tuple      =     state_dict["model"].pop("final_proj.0.bias"  )
      _lowercase    :   List[str]      =     os.path.join(snake_case	,       "converted.pt"  )
      torch.save(snake_case	,       snake_case  )
   else:
      _lowercase    :   List[Any]      =     DataaVecAudioForCTC(snake_case  )
      _lowercase    :   Tuple      =     checkpoint_path

   def load_dataavec(snake_case  ):
      _lowercase    :   Optional[Any]      =     fairseq.checkpoint_utils.load_model_ensemble_and_task([path]  )
      return model[0].eval()

   _lowercase    :   Dict      =     load_dataavec(snake_case  )

   recursively_load_weights(snake_case	,       snake_case	,       not is_finetuned  )

   _lowercase    :   Optional[int]      =     WavaVecaProcessor.from_pretrained("facebook/wav2vec2-large-lv60"  )

   _lowercase    :   List[Any]      =     load_dataset("patrickvonplaten/librispeech_asr_dummy"	,       "clean"	,       split="validation"  )
   _lowercase    :   Union[str, Any]      =     [x["array"] for x in ds[:4]["audio"]]

   _lowercase    :   List[str]      =     processor(snake_case	,       return_tensors="pt"	,       padding=snake_case  )

   _lowercase    :   Any      =     inputs.input_values
   _lowercase    :   Union[str, Any]      =     inputs.attention_mask
   #    input_values = inputs.input_values[:, :-1]
   #    attention_mask = inputs.attention_mask[:, :-1]

   hf_wavavec.eval()
   model.eval()
   if is_finetuned:
      _lowercase    :   Optional[int]      =     model(source=snake_case	,       padding_mask=(1 - attention_mask)	,       mask=snake_case	,       features_only=snake_case  )[
          "encoder_out"
      ].transpose(0	,       1  )
      _lowercase    :   List[Any]      =     hf_wavavec(snake_case	,       attention_mask=snake_case  )["logits"]

      _lowercase    :   Any      =     torch.argmax(snake_case	,       dim=-1  )
      _lowercase    :   List[Any]      =     processor.batch_decode(snake_case  )

      print(F'''Expected Output: {ds[:4]['text']}, Pred: {output_string}'''  )
   else:
      _lowercase    :   List[Any]      =     model(source=snake_case	,       padding_mask=(1 - attention_mask)	,       mask=snake_case	,       features_only=snake_case  )[
          "layer_results"
      ][-1][0].transpose(0	,       1  )
      _lowercase    :   str      =     hf_wavavec(snake_case	,       attention_mask=snake_case  )["last_hidden_state"]

   print(our_output.shape	,       their_output.shape  )
   _lowercase    :   List[Any]      =     torch.max(torch.abs(our_output - their_output  )  ).item()
   print(F'''max_absolute_diff = {max_absolute_diff}'''  )  # ~ 1e-7
   _lowercase    :   int      =     torch.allclose(snake_case	,       snake_case	,       atol=1E-3  )
   print("Do both models output the same tensors?"	,       "🔥" if success else "💩"  )
   if not success:
      raise Exception("Something went wRoNg"  )

   hf_wavavec.save_pretrained(snake_case  )

   if is_finetuned:
      processor.save_pretrained(snake_case  )
   else:
      processor.feature_extractor.save_pretrained(snake_case  )


if __name__ == "__main__":
    _snake_case     						=						argparse.ArgumentParser()
    parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
    parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
    parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
    parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
    parser.add_argument(
        '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
    )
    _snake_case     						=						parser.parse_args()
    convert_wavaveca_checkpoint(
        args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
    )









'''simple docstring'''
import unittest

import numpy as np
from datasets import load_dataset

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 SegformerImageProcessor


class      a__						(							unittest.TestCase						):


   def __init__(				self    ,       _UpperCamelCase    ,       _UpperCamelCase=7    ,       _UpperCamelCase=3    ,       _UpperCamelCase=30    ,       _UpperCamelCase=400    ,       _UpperCamelCase=True    ,       _UpperCamelCase=None    ,       _UpperCamelCase=True    ,       _UpperCamelCase=[0.5, 0.5, 0.5]    ,       _UpperCamelCase=[0.5, 0.5, 0.5]    ,       _UpperCamelCase=False    ,       ):





      """simple docstring"""





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






   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      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_reduce_labels": self.do_reduce_labels,
      }







def       _A	(			)    ->			List[Any]:
   _lowercase    :   List[str]      =     load_dataset("hf-internal-testing/fixtures_ade20k"	,							split="test"  )

   _lowercase    :   Union[str, Any]      =     Image.open(dataset[0]["file"]  )
   _lowercase    :   Optional[int]      =     Image.open(dataset[1]["file"]  )

   return image, map







def       _A	(			)    ->			Optional[int]:
   _lowercase    :   List[Any]      =     load_dataset("hf-internal-testing/fixtures_ade20k"	,							split="test"  )

   _lowercase    :   int      =     Image.open(dataset[0]["file"]  )
   _lowercase    :   str      =     Image.open(dataset[1]["file"]  )
   _lowercase    :   Union[str, Any]      =     Image.open(dataset[2]["file"]  )
   _lowercase    :   Union[str, Any]      =     Image.open(dataset[3]["file"]  )

   return [imagea, imagea], [mapa, mapa]


@require_torch
@require_vision
class      a__						(							lowerCamelCase_						,   unittest.TestCase						):
   _SCREAMING_SNAKE_CASE					:  Union[str, Any]			 =							SegformerImageProcessor if is_vision_available() else None


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Union[str, Any]      =     SegformerImageProcessingTester(self						)


   @property
   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      return self.image_processor_tester.prepare_image_processor_dict()


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   List[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_reduce_labels"						)						)


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Dict      =     self.image_processing_class.from_dict(self.image_processor_dict						)
      self.assertEqual(image_processor.size    ,       {"height": 30, "width": 30}						)
      self.assertEqual(image_processor.do_reduce_labels    ,       _UpperCamelCase						)

      _lowercase    :   Tuple      =     self.image_processing_class.from_dict(self.image_processor_dict    ,       size=42    ,       reduce_labels=_UpperCamelCase						)
      self.assertEqual(image_processor.size    ,       {"height": 42, "width": 42}						)
      self.assertEqual(image_processor.do_reduce_labels    ,       _UpperCamelCase						)


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      pass


   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   List[Any]      =     self.image_processing_class(**self.image_processor_dict						)
      # create random PIL images
      _lowercase    :   str      =     prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=_UpperCamelCase						)
      for image in image_inputs:
         self.assertIsInstance(_UpperCamelCase    ,       Image.Image						)

      # Test not batched input
      _lowercase    :   Optional[int]      =     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    :   int      =     image_processing(_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 		_lowerCamelCase     (				self						):





      """simple docstring"""





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

      # Test not batched input
      _lowercase    :   Dict      =     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(_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 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   List[str]      =     self.image_processing_class(**self.image_processor_dict						)
      # create random PyTorch tensors
      _lowercase    :   List[Any]      =     prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=_UpperCamelCase    ,       torchify=_UpperCamelCase						)
      for image in image_inputs:
         self.assertIsInstance(_UpperCamelCase    ,       torch.Tensor						)

      # Test not batched input
      _lowercase    :   Optional[int]      =     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(_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 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   Union[str, Any]      =     self.image_processing_class(**self.image_processor_dict						)
      # create random PyTorch tensors
      _lowercase    :   Tuple      =     prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=_UpperCamelCase    ,       torchify=_UpperCamelCase						)
      _lowercase    :   Tuple      =     []
      for image in image_inputs:
         self.assertIsInstance(_UpperCamelCase    ,       torch.Tensor						)
         maps.append(torch.zeros(image.shape[-2:]						).long()						)

      # Test not batched input
      _lowercase    :   List[str]      =     image_processing(image_inputs[0]    ,       maps[0]    ,       return_tensors="pt"						)
      self.assertEqual(
          encoding["pixel_values"].shape    ,       (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(
          encoding["labels"].shape    ,       (
              1,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(encoding["labels"].dtype    ,       torch.long						)
      self.assertTrue(encoding["labels"].min().item() >= 0						)
      self.assertTrue(encoding["labels"].max().item() <= 255						)

      # Test batched
      _lowercase    :   Optional[int]      =     image_processing(_UpperCamelCase    ,       _UpperCamelCase    ,       return_tensors="pt"						)
      self.assertEqual(
          encoding["pixel_values"].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"],
          )    ,       )
      self.assertEqual(
          encoding["labels"].shape    ,       (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(encoding["labels"].dtype    ,       torch.long						)
      self.assertTrue(encoding["labels"].min().item() >= 0						)
      self.assertTrue(encoding["labels"].max().item() <= 255						)

      # Test not batched input (PIL images)
      _lowercase  ,   _lowercase    :   Optional[int]      =     prepare_semantic_single_inputs()

      _lowercase    :   int      =     image_processing(_UpperCamelCase    ,       _UpperCamelCase    ,       return_tensors="pt"						)
      self.assertEqual(
          encoding["pixel_values"].shape    ,       (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(
          encoding["labels"].shape    ,       (
              1,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(encoding["labels"].dtype    ,       torch.long						)
      self.assertTrue(encoding["labels"].min().item() >= 0						)
      self.assertTrue(encoding["labels"].max().item() <= 255						)

      # Test batched input (PIL images)
      _lowercase  ,   _lowercase    :   Dict      =     prepare_semantic_batch_inputs()

      _lowercase    :   List[str]      =     image_processing(_UpperCamelCase    ,       _UpperCamelCase    ,       return_tensors="pt"						)
      self.assertEqual(
          encoding["pixel_values"].shape    ,       (
              2,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(
          encoding["labels"].shape    ,       (
              2,
              self.image_processor_tester.size["height"],
              self.image_processor_tester.size["width"],
          )    ,       )
      self.assertEqual(encoding["labels"].dtype    ,       torch.long						)
      self.assertTrue(encoding["labels"].min().item() >= 0						)
      self.assertTrue(encoding["labels"].max().item() <= 255						)






   def 		_lowerCamelCase     (				self						):





      """simple docstring"""





      _lowercase    :   str      =     self.image_processing_class(**self.image_processor_dict						)

      # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
      _lowercase  ,   _lowercase    :   str      =     prepare_semantic_single_inputs()
      _lowercase    :   Optional[int]      =     image_processing(_UpperCamelCase    ,       _UpperCamelCase    ,       return_tensors="pt"						)
      self.assertTrue(encoding["labels"].min().item() >= 0						)
      self.assertTrue(encoding["labels"].max().item() <= 150						)

      _lowercase    :   str      =     True
      _lowercase    :   List[str]      =     image_processing(_UpperCamelCase    ,       _UpperCamelCase    ,       return_tensors="pt"						)
      self.assertTrue(encoding["labels"].min().item() >= 0						)
      self.assertTrue(encoding["labels"].max().item() <= 255						)






