



'''simple docstring'''






import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


lowerCAmelCase:      Optional[int]		 =		get_tests_dir('fixtures/dummy_feature_extractor_config.json')
lowerCAmelCase:      int		 =		get_tests_dir('fixtures/vocab.json')
lowerCAmelCase:      str		 =		get_tests_dir('fixtures')

class 							a__(      unittest.TestCase			):
    lowercase__				=					["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]







    def     lowercase_ (   self				:						int			):
      a		:      Optional[int]       =  0







    def     lowercase_ (   self				:						Optional[int]			):
      a		:      str       =  AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h'			)
      self.assertIsInstance(__snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						Tuple			):
      with tempfile.TemporaryDirectory() as tmpdirname:
        a		:      int       =  WavaVecaConfig()
        a		:      Any       =  AutoProcessor.from_pretrained('facebook/wav2vec2-base-960h'			)

        # save in new folder
        model_config.save_pretrained(__snake_case			)
        processor.save_pretrained(__snake_case			)

        a		:      str       =  AutoProcessor.from_pretrained(__snake_case			)

      self.assertIsInstance(__snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]			):
      with tempfile.TemporaryDirectory() as tmpdirname:
        # copy relevant files
        copyfile(__snake_case		,    os.path.join(__snake_case		,    __snake_case			)			)
        copyfile(__snake_case		,    os.path.join(__snake_case		,    'vocab.json'			)			)

        a		:      Optional[Any]       =  AutoProcessor.from_pretrained(__snake_case			)

      self.assertIsInstance(__snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						Dict			):
      with tempfile.TemporaryDirectory() as tmpdirname:
        a		:      Dict       =  WavaVecaFeatureExtractor()
        a		:      Tuple       =  AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h'			)

        a		:      Any       =  WavaVecaProcessor(__snake_case		,    __snake_case			)

        # save in new folder
        processor.save_pretrained(__snake_case			)

        # drop `processor_class` in tokenizer
        with open(os.path.join(__snake_case		,    __snake_case			)		,    'r'			) as f:
          a		:      Dict       =  json.load(__snake_case			)
          config_dict.pop('processor_class'			)

        with open(os.path.join(__snake_case		,    __snake_case			)		,    'w'			) as f:
          f.write(json.dumps(__snake_case			)			)

        a		:      Optional[int]       =  AutoProcessor.from_pretrained(__snake_case			)

      self.assertIsInstance(__snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						Optional[int]			):
      with tempfile.TemporaryDirectory() as tmpdirname:
        a		:      List[Any]       =  WavaVecaFeatureExtractor()
        a		:      Any       =  AutoTokenizer.from_pretrained('facebook/wav2vec2-base-960h'			)

        a		:      int       =  WavaVecaProcessor(__snake_case		,    __snake_case			)

        # save in new folder
        processor.save_pretrained(__snake_case			)

        # drop `processor_class` in feature extractor
        with open(os.path.join(__snake_case		,    __snake_case			)		,    'r'			) as f:
          a		:      Any       =  json.load(__snake_case			)
          config_dict.pop('processor_class'			)

        with open(os.path.join(__snake_case		,    __snake_case			)		,    'w'			) as f:
          f.write(json.dumps(__snake_case			)			)

        a		:      Union[str, Any]       =  AutoProcessor.from_pretrained(__snake_case			)

      self.assertIsInstance(__snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						str			):
      with tempfile.TemporaryDirectory() as tmpdirname:
        a		:      List[str]       =  WavaVecaConfig(processor_class='Wav2Vec2Processor'			)
        model_config.save_pretrained(__snake_case			)
        # copy relevant files
        copyfile(__snake_case		,    os.path.join(__snake_case		,    'vocab.json'			)			)
        # create emtpy sample processor
        with open(os.path.join(__snake_case		,    __snake_case			)		,    'w'			) as f:
          f.write('{}'			)

        a		:      int       =  AutoProcessor.from_pretrained(__snake_case			)

      self.assertIsInstance(__snake_case		,    __snake_case			)







    def     lowercase_ (   self				:						Any			):
      # If remote code is not set, we will time out when asking whether to load the model.
      with self.assertRaises(__snake_case			):
        a		:      List[str]       =  AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'			)
      # If remote code is disabled, we can't load this config.
      with self.assertRaises(__snake_case			):
        a		:      Optional[int]       =  AutoProcessor.from_pretrained(
            'hf-internal-testing/test_dynamic_processor'		,    trust_remote_code=__snake_case			)

      a		:      Optional[Any]       =  AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'		,    trust_remote_code=__snake_case			)
      self.assertTrue(processor.special_attribute_present			)
      self.assertEqual(processor.__class__.__name__		,    'NewProcessor'			)

      a		:      Dict       =  processor.feature_extractor
      self.assertTrue(feature_extractor.special_attribute_present			)
      self.assertEqual(feature_extractor.__class__.__name__		,    'NewFeatureExtractor'			)

      a		:      Any       =  processor.tokenizer
      self.assertTrue(tokenizer.special_attribute_present			)
      if is_tokenizers_available():
        self.assertEqual(tokenizer.__class__.__name__		,    'NewTokenizerFast'			)

        # Test we can also load the slow version
        a		:      Tuple       =  AutoProcessor.from_pretrained(
            'hf-internal-testing/test_dynamic_processor'		,    trust_remote_code=__snake_case		,    use_fast=__snake_case			)
        a		:      List[str]       =  new_processor.tokenizer
        self.assertTrue(new_tokenizer.special_attribute_present			)
        self.assertEqual(new_tokenizer.__class__.__name__		,    'NewTokenizer'			)
      else:
        self.assertEqual(tokenizer.__class__.__name__		,    'NewTokenizer'			)







    def     lowercase_ (   self				:						Any			):
      try:
        AutoConfig.register('custom'		,    __snake_case			)
        AutoFeatureExtractor.register(__snake_case		,    __snake_case			)
        AutoTokenizer.register(__snake_case		,    slow_tokenizer_class=__snake_case			)
        AutoProcessor.register(__snake_case		,    __snake_case			)
        # Trying to register something existing in the Transformers library will raise an error
        with self.assertRaises(__snake_case			):
          AutoProcessor.register(__snake_case		,    __snake_case			)

        # Now that the config is registered, it can be used as any other config with the auto-API
        a		:      Tuple       =  CustomFeatureExtractor.from_pretrained(__snake_case			)

        with tempfile.TemporaryDirectory() as tmp_dir:
          a		:      List[Any]       =  os.path.join(__snake_case		,    'vocab.txt'			)
          with open(__snake_case		,    'w'		,    encoding='utf-8'			) as vocab_writer:
            vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]			)			)
          a		:      str       =  CustomTokenizer(__snake_case			)

        a		:      str       =  CustomProcessor(__snake_case		,    __snake_case			)

        with tempfile.TemporaryDirectory() as tmp_dir:
          processor.save_pretrained(__snake_case			)
          a		:      List[Any]       =  AutoProcessor.from_pretrained(__snake_case			)
          self.assertIsInstance(__snake_case		,    __snake_case			)

      finally:
        if "custom" in CONFIG_MAPPING._extra_content:
          del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
          del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
        if CustomConfig in TOKENIZER_MAPPING._extra_content:
          del TOKENIZER_MAPPING._extra_content[CustomConfig]
        if CustomConfig in PROCESSOR_MAPPING._extra_content:
          del PROCESSOR_MAPPING._extra_content[CustomConfig]







    def     lowercase_ (   self				:						str			):

      class 							a__(      lowerCamelCase__			):
          lowercase__				=					False

      class 							a__(      lowerCamelCase__			):
          lowercase__				=					False

      class 							a__(      lowerCamelCase__			):
          lowercase__				=					"""AutoFeatureExtractor"""
          lowercase__				=					"""AutoTokenizer"""
          lowercase__				=					False

      try:
        AutoConfig.register('custom'		,    __snake_case			)
        AutoFeatureExtractor.register(__snake_case		,    __snake_case			)
        AutoTokenizer.register(__snake_case		,    slow_tokenizer_class=__snake_case			)
        AutoProcessor.register(__snake_case		,    __snake_case			)
        # If remote code is not set, the default is to use local classes.
        a		:      Dict       =  AutoProcessor.from_pretrained('hf-internal-testing/test_dynamic_processor'			)
        self.assertEqual(processor.__class__.__name__		,    'NewProcessor'			)
        self.assertFalse(processor.special_attribute_present			)
        self.assertFalse(processor.feature_extractor.special_attribute_present			)
        self.assertFalse(processor.tokenizer.special_attribute_present			)

        # If remote code is disabled, we load the local ones.
        a		:      Union[str, Any]       =  AutoProcessor.from_pretrained(
            'hf-internal-testing/test_dynamic_processor'		,    trust_remote_code=__snake_case			)
        self.assertEqual(processor.__class__.__name__		,    'NewProcessor'			)
        self.assertFalse(processor.special_attribute_present			)
        self.assertFalse(processor.feature_extractor.special_attribute_present			)
        self.assertFalse(processor.tokenizer.special_attribute_present			)

        # If remote is enabled, we load from the Hub.
        a		:      Union[str, Any]       =  AutoProcessor.from_pretrained(
            'hf-internal-testing/test_dynamic_processor'		,    trust_remote_code=__snake_case			)
        self.assertEqual(processor.__class__.__name__		,    'NewProcessor'			)
        self.assertTrue(processor.special_attribute_present			)
        self.assertTrue(processor.feature_extractor.special_attribute_present			)
        self.assertTrue(processor.tokenizer.special_attribute_present			)

      finally:
        if "custom" in CONFIG_MAPPING._extra_content:
          del CONFIG_MAPPING._extra_content["custom"]
        if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
          del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
        if CustomConfig in TOKENIZER_MAPPING._extra_content:
          del TOKENIZER_MAPPING._extra_content[CustomConfig]
        if CustomConfig in PROCESSOR_MAPPING._extra_content:
          del PROCESSOR_MAPPING._extra_content[CustomConfig]







    def     lowercase_ (   self				:						Dict			):
      a		:      int       =  AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-bert'			)
      self.assertEqual(processor.__class__.__name__		,    'BertTokenizerFast'			)







    def     lowercase_ (   self				:						List[Any]			):
      a		:      str       =  AutoProcessor.from_pretrained('hf-internal-testing/tiny-random-convnext'			)
      self.assertEqual(processor.__class__.__name__		,    'ConvNextImageProcessor'			)

@is_staging_test
class 							a__(      unittest.TestCase			):
    lowercase__				=					["""[UNK]""", """[CLS]""", """[SEP]""", """[PAD]""", """[MASK]""", """bla""", """blou"""]







    @classmethod
    def     lowercase_ (   cls				:						List[str]			):
      a		:      List[Any]       =  TOKEN
      HfFolder.save_token(__snake_case			)







    @classmethod
    def     lowercase_ (   cls				:						Any			):
      try:
        delete_repo(token=cls._token		,    repo_id='test-processor'			)
      except HTTPError:
        pass

      try:
        delete_repo(token=cls._token		,    repo_id='valid_org/test-processor-org'			)
      except HTTPError:
        pass

      try:
        delete_repo(token=cls._token		,    repo_id='test-dynamic-processor'			)
      except HTTPError:
        pass







    def     lowercase_ (   self				:						Tuple			):
      a		:      str       =  WavaVecaProcessor.from_pretrained(__snake_case			)
      with tempfile.TemporaryDirectory() as tmp_dir:
        processor.save_pretrained(
            os.path.join(__snake_case		,    'test-processor'			)		,    push_to_hub=__snake_case		,    use_auth_token=self._token			)

        a		:      Union[str, Any]       =  WavaVecaProcessor.from_pretrained(F"""{USER}/test-processor"""			)
        for k, v in processor.feature_extractor.__dict__.items():
          self.assertEqual(__snake_case		,    getattr(new_processor.feature_extractor		,    __snake_case			)			)
        self.assertDictEqual(new_processor.tokenizer.get_vocab()		,    processor.tokenizer.get_vocab()			)







    def     lowercase_ (   self				:						Dict			):
      a		:      int       =  WavaVecaProcessor.from_pretrained(__snake_case			)

      with tempfile.TemporaryDirectory() as tmp_dir:
        processor.save_pretrained(
            os.path.join(__snake_case		,    'test-processor-org'			)		,    push_to_hub=__snake_case		,    use_auth_token=self._token		,    organization='valid_org'		,    )

        a		:      Any       =  WavaVecaProcessor.from_pretrained('valid_org/test-processor-org'			)
        for k, v in processor.feature_extractor.__dict__.items():
          self.assertEqual(__snake_case		,    getattr(new_processor.feature_extractor		,    __snake_case			)			)
        self.assertDictEqual(new_processor.tokenizer.get_vocab()		,    processor.tokenizer.get_vocab()			)







    def     lowercase_ (   self				:						Any			):
      CustomFeatureExtractor.register_for_auto_class()
      CustomTokenizer.register_for_auto_class()
      CustomProcessor.register_for_auto_class()

      a		:      Dict       =  CustomFeatureExtractor.from_pretrained(__snake_case			)

      with tempfile.TemporaryDirectory() as tmp_dir:
        a		:      Dict       =  os.path.join(__snake_case		,    'vocab.txt'			)
        with open(__snake_case		,    'w'		,    encoding='utf-8'			) as vocab_writer:
          vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]			)			)
        a		:      List[Any]       =  CustomTokenizer(__snake_case			)

      a		:      Optional[Any]       =  CustomProcessor(__snake_case		,    __snake_case			)

      with tempfile.TemporaryDirectory() as tmp_dir:
        create_repo(F"""{USER}/test-dynamic-processor"""		,    token=self._token			)
        a		:      str       =  Repository(__snake_case		,    clone_from=F"""{USER}/test-dynamic-processor"""		,    token=self._token			)
        processor.save_pretrained(__snake_case			)

        # This has added the proper auto_map field to the feature extractor config
        self.assertDictEqual(
            processor.feature_extractor.auto_map		,    {
                'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor',
                'AutoProcessor': 'custom_processing.CustomProcessor',
            }		,    )

        # This has added the proper auto_map field to the tokenizer config
        with open(os.path.join(__snake_case		,    'tokenizer_config.json'			)			) as f:
          a		:      Union[str, Any]       =  json.load(__snake_case			)
        self.assertDictEqual(
            tokenizer_config['auto_map']		,    {
                'AutoTokenizer': ['custom_tokenization.CustomTokenizer', None],
                'AutoProcessor': 'custom_processing.CustomProcessor',
            }		,    )

        # The code has been copied from fixtures
        self.assertTrue(os.path.isfile(os.path.join(__snake_case		,    'custom_feature_extraction.py'			)			)			)
        self.assertTrue(os.path.isfile(os.path.join(__snake_case		,    'custom_tokenization.py'			)			)			)
        self.assertTrue(os.path.isfile(os.path.join(__snake_case		,    'custom_processing.py'			)			)			)

        repo.push_to_hub()

      a		:      Any       =  AutoProcessor.from_pretrained(F"""{USER}/test-dynamic-processor"""		,    trust_remote_code=__snake_case			)
      # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
      self.assertEqual(new_processor.__class__.__name__		,    'CustomProcessor'			)




'''simple docstring'''






from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
     import torch


lowerCAmelCase:      Union[str, Any]		 =		logging.get_logger(__name__)

class 							a__(      lowerCamelCase__			):
    lowercase__				=					["""pixel_values"""]







    def __init__(   self				:						int		,    __snake_case				:						bool = True		,    __snake_case				:						Optional[Dict[str, int]] = None		,    __snake_case				:						PILImageResampling = PILImageResampling.BILINEAR		,    __snake_case				:						bool = True		,    __snake_case				:						Dict[str, int] = None		,    __snake_case				:						bool = True		,    __snake_case				:						Union[int, float] = 1 / 2_55		,    __snake_case				:						bool = True		,    __snake_case				:						Optional[Union[float, List[float]]] = None		,    __snake_case				:						Optional[Union[float, List[float]]] = None		,    **__snake_case				:						List[str]		,    ):
      super().__init__(**__snake_case			)
      a		:      Dict       =  size if size is not None else {'shortest_edge': 2_56}
      a		:      Optional[int]       =  get_size_dict(__snake_case		,    default_to_square=__snake_case			)
      a		:      List[str]       =  crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
      a		:      Dict       =  get_size_dict(__snake_case		,    param_name='crop_size'			)
      a		:      Optional[int]       =  do_resize
      a		:      Union[str, Any]       =  size
      a		:      Optional[Any]       =  resample
      a		:      int       =  do_center_crop
      a		:      List[str]       =  crop_size
      a		:      Tuple       =  do_rescale
      a		:      Any       =  rescale_factor
      a		:      str       =  do_normalize
      a		:      int       =  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
      a		:      List[str]       =  image_std if image_std is not None else IMAGENET_STANDARD_STD







    def     lowercase_ (   self				:						str		,    __snake_case				:						np.ndarray		,    __snake_case				:						Dict[str, int]		,    __snake_case				:						PILImageResampling = PILImageResampling.BICUBIC		,    __snake_case				:						Optional[Union[str, ChannelDimension]] = None		,    **__snake_case				:						Any		,    ):
      a		:      str       =  get_size_dict(__snake_case		,    default_to_square=__snake_case			)
      if "shortest_edge" not in size:
        raise ValueError(F"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""			)
      a		:      str       =  get_resize_output_image_size(__snake_case		,    size=size['shortest_edge']		,    default_to_square=__snake_case			)
      return resize(__snake_case		,    size=__snake_case		,    resample=__snake_case		,    data_format=__snake_case		,    **__snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]		,    __snake_case				:						np.ndarray		,    __snake_case				:						Dict[str, int]		,    __snake_case				:						Optional[Union[str, ChannelDimension]] = None		,    **__snake_case				:						Any		,    ):
      a		:      Any       =  get_size_dict(__snake_case			)
      if "height" not in size or "width" not in size:
        raise ValueError(F"""The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"""			)
      return center_crop(__snake_case		,    size=(size['height'], size['width'])		,    data_format=__snake_case		,    **__snake_case			)







    def     lowercase_ (   self				:						str		,    __snake_case				:						np.ndarray		,    __snake_case				:						float		,    __snake_case				:						Optional[Union[str, ChannelDimension]] = None		,    **__snake_case				:						str			):
      return rescale(__snake_case		,    scale=__snake_case		,    data_format=__snake_case		,    **__snake_case			)







    def     lowercase_ (   self				:						Optional[int]		,    __snake_case				:						np.ndarray		,    __snake_case				:						Union[float, List[float]]		,    __snake_case				:						Union[float, List[float]]		,    __snake_case				:						Optional[Union[str, ChannelDimension]] = None		,    **__snake_case				:						List[str]		,    ):
      return normalize(__snake_case		,    mean=__snake_case		,    std=__snake_case		,    data_format=__snake_case		,    **__snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]		,    __snake_case				:						ImageInput		,    __snake_case				:						Optional[bool] = None		,    __snake_case				:						Dict[str, int] = None		,    __snake_case				:						PILImageResampling = None		,    __snake_case				:						bool = None		,    __snake_case				:						Dict[str, int] = None		,    __snake_case				:						Optional[bool] = None		,    __snake_case				:						Optional[float] = None		,    __snake_case				:						Optional[bool] = None		,    __snake_case				:						Optional[Union[float, List[float]]] = None		,    __snake_case				:						Optional[Union[float, List[float]]] = None		,    __snake_case				:						Optional[Union[str, TensorType]] = None		,    __snake_case				:						Union[str, ChannelDimension] = ChannelDimension.FIRST		,    **__snake_case				:						Union[str, Any]		,    ):
      a		:      Dict       =  do_resize if do_resize is not None else self.do_resize
      a		:      str       =  size if size is not None else self.size
      a		:      Dict       =  get_size_dict(__snake_case		,    default_to_square=__snake_case			)
      a		:      Optional[int]       =  resample if resample is not None else self.resample
      a		:      List[str]       =  do_center_crop if do_center_crop is not None else self.do_center_crop
      a		:      int       =  crop_size if crop_size is not None else self.crop_size
      a		:      List[str]       =  get_size_dict(__snake_case		,    param_name='crop_size'			)
      a		:      Optional[Any]       =  do_rescale if do_rescale is not None else self.do_rescale
      a		:      List[str]       =  rescale_factor if rescale_factor is not None else self.rescale_factor
      a		:      List[Any]       =  do_normalize if do_normalize is not None else self.do_normalize
      a		:      Dict       =  image_mean if image_mean is not None else self.image_mean
      a		:      Dict       =  image_std if image_std is not None else self.image_std

      a		:      int       =  make_list_of_images(__snake_case			)

      if not valid_images(__snake_case			):
        raise ValueError(
            'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
            'torch.Tensor, tf.Tensor or jax.ndarray.'			)

      if do_resize and size is None:
        raise ValueError('Size must be specified if do_resize is True.'			)

      if do_center_crop and crop_size is None:
        raise ValueError('Crop size must be specified if do_center_crop is True.'			)

      if do_rescale and rescale_factor is None:
        raise ValueError('Rescale factor must be specified if do_rescale is True.'			)

      if do_normalize and (image_mean is None or image_std is None):
        raise ValueError('Image mean and std must be specified if do_normalize is True.'			)

      # All transformations expect numpy arrays.
      a		:      int       =  [to_numpy_array(__snake_case			) for image in images]

      if do_resize:
        a		:      List[Any]       =  [self.resize(image=__snake_case		,    size=__snake_case		,    resample=__snake_case			) for image in images]

      if do_center_crop:
        a		:      Any       =  [self.center_crop(image=__snake_case		,    size=__snake_case			) for image in images]

      if do_rescale:
        a		:      Union[str, Any]       =  [self.rescale(image=__snake_case		,    scale=__snake_case			) for image in images]

      if do_normalize:
        a		:      List[str]       =  [self.normalize(image=__snake_case		,    mean=__snake_case		,    std=__snake_case			) for image in images]

      a		:      str       =  [to_channel_dimension_format(__snake_case		,    __snake_case			) for image in images]

      a		:      Tuple       =  {'pixel_values': images}
      return BatchFeature(data=__snake_case		,    tensor_type=__snake_case			)







    def     lowercase_ (   self				:						List[Any]		,    __snake_case				:						Tuple		,    __snake_case				:						List[Tuple] = None			):
      a		:      Union[str, Any]       =  outputs.logits

      # Resize logits and compute semantic segmentation maps
      if target_sizes is not None:
        if len(__snake_case			) != len(__snake_case			):
          raise ValueError(
              'Make sure that you pass in as many target sizes as the batch dimension of the logits'			)

        if is_torch_tensor(__snake_case			):
          a		:      Optional[int]       =  target_sizes.numpy()

        a		:      Union[str, Any]       =  []

        for idx in range(len(__snake_case			)			):
          a		:      Dict       =  torch.nn.functional.interpolate(
              logits[idx].unsqueeze(dim=0			)		,    size=target_sizes[idx]		,    mode='bilinear'		,    align_corners=__snake_case			)
          a		:      Optional[Any]       =  resized_logits[0].argmax(dim=0			)
          semantic_segmentation.append(__snake_case			)
      else:
        a		:      List[Any]       =  logits.argmax(dim=1			)
        a		:      List[str]       =  [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]			)]

      return semantic_segmentation