


import argparse
import collections
import json
from pathlib import Path

import requests
import torch
import yaml
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    MobileViTImageProcessor,
    MobileViTVaConfig,
    MobileViTVaForImageClassification,
    MobileViTVaForSemanticSegmentation,
)
from transformers.utils import logging


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





def 	_UpperCAmelCase							(  UpperCAmelCase   :      str   ):
      """simple docstring"""




      print("""Loading config file..."""   )

      def flatten_yaml_as_dict(UpperCAmelCase   :      List[Any]    ,						UpperCAmelCase   :      int=""    ,						UpperCAmelCase   :      Dict="."   ):
            __lowerCamelCase  :   Optional[Any]							    =    []
            for k, v in d.items():
                  __lowerCamelCase  :   str							    =    parent_key + sep + k if parent_key else k
                  if isinstance(UpperCAmelCase    ,						collections.abc.MutableMapping   ):
                        items.extend(flatten_yaml_as_dict(UpperCAmelCase    ,						UpperCAmelCase    ,						sep=UpperCAmelCase   ).items()   )
                  else:
                        items.append((new_key, v)   )
            return dict(UpperCAmelCase   )

      __lowerCamelCase  :   List[str]							    =    argparse.Namespace()
      with open(UpperCAmelCase    ,						"""r"""   ) as yaml_file:
            try:
                  __lowerCamelCase  :   Optional[int]							    =    yaml.load(UpperCAmelCase    ,						Loader=yaml.FullLoader   )

                  __lowerCamelCase  :   int							    =    flatten_yaml_as_dict(UpperCAmelCase   )
                  for k, v in flat_cfg.items():
                        setattr(UpperCAmelCase    ,						UpperCAmelCase    ,						UpperCAmelCase   )
            except yaml.YAMLError as exc:
                  logger.error("""Error while loading config file: {}. Error message: {}""".format(UpperCAmelCase    ,						str(UpperCAmelCase   )   )   )
      return config





def 	_UpperCAmelCase							(  UpperCAmelCase   :      Optional[int]    ,						UpperCAmelCase   :      int   ):
      """simple docstring"""




      __lowerCamelCase  :   List[str]							    =    MobileViTVaConfig()

      __lowerCamelCase  :   List[Any]							    =    False

      # dataset
      if task_name.startswith("""imagenet1k_"""   ):
            __lowerCamelCase  :   List[Any]							    =    1_000
            if int(task_name.strip().split("""_"""   )[-1]   ) == 384:
                  __lowerCamelCase  :   List[Any]							    =    384
            else:
                  __lowerCamelCase  :   Optional[Any]							    =    256
            __lowerCamelCase  :   Optional[int]							    =    "imagenet-1k-id2label.json"
      elif task_name.startswith("""imagenet21k_to_1k_"""   ):
            __lowerCamelCase  :   Any							    =    21_000
            if int(task_name.strip().split("""_"""   )[-1]   ) == 384:
                  __lowerCamelCase  :   int							    =    384
            else:
                  __lowerCamelCase  :   str							    =    256
            __lowerCamelCase  :   str							    =    "imagenet-22k-id2label.json"
      elif task_name.startswith("""ade20k_"""   ):
            __lowerCamelCase  :   Optional[int]							    =    151
            __lowerCamelCase  :   Optional[Any]							    =    512
            __lowerCamelCase  :   List[str]							    =    "ade20k-id2label.json"
            __lowerCamelCase  :   List[Any]							    =    True
      elif task_name.startswith("""voc_"""   ):
            __lowerCamelCase  :   Optional[int]							    =    21
            __lowerCamelCase  :   Tuple							    =    512
            __lowerCamelCase  :   List[Any]							    =    "pascal-voc-id2label.json"
            __lowerCamelCase  :   Any							    =    True

      # orig_config
      __lowerCamelCase  :   int							    =    load_orig_config_file(UpperCAmelCase   )
      assert getattr(UpperCAmelCase    ,						"""model.classification.name"""    ,						-1   ) == "mobilevit_v2", "Invalid model"
      __lowerCamelCase  :   int							    =    getattr(UpperCAmelCase    ,						"""model.classification.mitv2.width_multiplier"""    ,						1.0   )
      assert (
          getattr(UpperCAmelCase    ,						"""model.classification.mitv2.attn_norm_layer"""    ,						-1   ) == "layer_norm_2d"
      ), "Norm layers other than layer_norm_2d is not supported"
      __lowerCamelCase  :   Any							    =    getattr(UpperCAmelCase    ,						"""model.classification.activation.name"""    ,						"""swish"""   )
      # config.image_size == getattr(orig_config,  'sampler.bs.crop_size_width', 256)

      if is_segmentation_model:
            __lowerCamelCase  :   str							    =    getattr(UpperCAmelCase    ,						"""model.segmentation.output_stride"""    ,						16   )
            if "_deeplabv3" in task_name:
                  __lowerCamelCase  :   Optional[Any]							    =    getattr(UpperCAmelCase    ,						"""model.segmentation.deeplabv3.aspp_rates"""    ,						[12, 24, 36]   )
                  __lowerCamelCase  :   Optional[int]							    =    getattr(UpperCAmelCase    ,						"""model.segmentation.deeplabv3.aspp_out_channels"""    ,						512   )
                  __lowerCamelCase  :   str							    =    getattr(UpperCAmelCase    ,						"""model.segmentation.deeplabv3.aspp_dropout"""    ,						0.1   )

    # id2label
      __lowerCamelCase  :   Union[str, Any]							    =    "huggingface/label-files"
      __lowerCamelCase  :   Union[str, Any]							    =    json.load(open(hf_hub_download(UpperCAmelCase    ,						UpperCAmelCase    ,						repo_type="""dataset"""   )    ,						"""r"""   )   )
      __lowerCamelCase  :   Optional[int]							    =    {int(UpperCAmelCase   ): v for k, v in idalabel.items()}
      __lowerCamelCase  :   Dict							    =    idalabel
      __lowerCamelCase  :   Union[str, Any]							    =    {v: k for k, v in idalabel.items()}

      return config





def 	_UpperCAmelCase							(  UpperCAmelCase   :      List[str]    ,						UpperCAmelCase   :      int    ,						UpperCAmelCase   :      Dict   ):
      """simple docstring"""




      __lowerCamelCase  :   Union[str, Any]							    =    dct.pop(UpperCAmelCase   )
      __lowerCamelCase  :   int							    =    val





def 	_UpperCAmelCase							(  UpperCAmelCase   :      Any    ,						UpperCAmelCase   :      int=False   ):
      """simple docstring"""




      if base_model:
            __lowerCamelCase  :   str							    =    ""
      else:
            __lowerCamelCase  :   Optional[Any]							    =    "mobilevitv2."

      __lowerCamelCase  :   List[str]							    =    []
      for k in state_dict.keys():
            if k[:8] == "encoder.":
                  __lowerCamelCase  :   Tuple							    =    k[8:]
            else:
                  __lowerCamelCase  :   Union[str, Any]							    =    k

            if ".block." in k:
                  __lowerCamelCase  :   Any							    =    k_new.replace(""".block."""    ,						"""."""   )
            if ".conv." in k:
                  __lowerCamelCase  :   List[str]							    =    k_new.replace(""".conv."""    ,						""".convolution."""   )
            if ".norm." in k:
                  __lowerCamelCase  :   Tuple							    =    k_new.replace(""".norm."""    ,						""".normalization."""   )

            if "conv_1." in k:
                  __lowerCamelCase  :   Tuple							    =    k_new.replace("""conv_1."""    ,						f"""{model_prefix}conv_stem."""   )
            for i in [1, 2]:
                  if f"""layer_{i}.""" in k:
                        __lowerCamelCase  :   Optional[int]							    =    k_new.replace(f"""layer_{i}."""    ,						f"""{model_prefix}encoder.layer.{i-1}.layer."""   )
            if ".exp_1x1." in k:
                  __lowerCamelCase  :   str							    =    k_new.replace(""".exp_1x1."""    ,						""".expand_1x1."""   )
            if ".red_1x1." in k:
                  __lowerCamelCase  :   Tuple							    =    k_new.replace(""".red_1x1."""    ,						""".reduce_1x1."""   )

            for i in [3, 4, 5]:
                  if f"""layer_{i}.0.""" in k:
                        __lowerCamelCase  :   str							    =    k_new.replace(f"""layer_{i}.0."""    ,						f"""{model_prefix}encoder.layer.{i-1}.downsampling_layer."""   )
                  if f"""layer_{i}.1.local_rep.0.""" in k:
                        __lowerCamelCase  :   Any							    =    k_new.replace(f"""layer_{i}.1.local_rep.0."""    ,						f"""{model_prefix}encoder.layer.{i-1}.conv_kxk."""   )
                  if f"""layer_{i}.1.local_rep.1.""" in k:
                        __lowerCamelCase  :   str							    =    k_new.replace(f"""layer_{i}.1.local_rep.1."""    ,						f"""{model_prefix}encoder.layer.{i-1}.conv_1x1."""   )

            for i in [3, 4, 5]:
                  if i == 3:
                        __lowerCamelCase  :   str							    =    [0, 1]
                  elif i == 4:
                        __lowerCamelCase  :   Union[str, Any]							    =    [0, 1, 2, 3]
                  elif i == 5:
                        __lowerCamelCase  :   str							    =    [0, 1, 2]

                  for j in j_in:
                        if f"""layer_{i}.1.global_rep.{j}.""" in k:
                              __lowerCamelCase  :   Dict							    =    k_new.replace(
                                  f"""layer_{i}.1.global_rep.{j}."""    ,						f"""{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}."""   )
                  if f"""layer_{i}.1.global_rep.{j+1}.""" in k:
                        __lowerCamelCase  :   int							    =    k_new.replace(
                            f"""layer_{i}.1.global_rep.{j+1}."""    ,						f"""{model_prefix}encoder.layer.{i-1}.layernorm."""   )

                  if f"""layer_{i}.1.conv_proj.""" in k:
                        __lowerCamelCase  :   Union[str, Any]							    =    k_new.replace(f"""layer_{i}.1.conv_proj."""    ,						f"""{model_prefix}encoder.layer.{i-1}.conv_projection."""   )

            if "pre_norm_attn.0." in k:
                  __lowerCamelCase  :   int							    =    k_new.replace("""pre_norm_attn.0."""    ,						"""layernorm_before."""   )
            if "pre_norm_attn.1." in k:
                  __lowerCamelCase  :   List[Any]							    =    k_new.replace("""pre_norm_attn.1."""    ,						"""attention."""   )
            if "pre_norm_ffn.0." in k:
                  __lowerCamelCase  :   Optional[Any]							    =    k_new.replace("""pre_norm_ffn.0."""    ,						"""layernorm_after."""   )
            if "pre_norm_ffn.1." in k:
                  __lowerCamelCase  :   Dict							    =    k_new.replace("""pre_norm_ffn.1."""    ,						"""ffn.conv1."""   )
            if "pre_norm_ffn.3." in k:
                  __lowerCamelCase  :   Optional[int]							    =    k_new.replace("""pre_norm_ffn.3."""    ,						"""ffn.conv2."""   )

            if "classifier.1." in k:
                  __lowerCamelCase  :   Any							    =    k_new.replace("""classifier.1."""    ,						"""classifier."""   )

            if "seg_head." in k:
                  __lowerCamelCase  :   Optional[Any]							    =    k_new.replace("""seg_head."""    ,						"""segmentation_head."""   )
            if ".aspp_layer." in k:
                  __lowerCamelCase  :   Tuple							    =    k_new.replace(""".aspp_layer."""    ,						"""."""   )
            if ".aspp_pool." in k:
                  __lowerCamelCase  :   Dict							    =    k_new.replace(""".aspp_pool."""    ,						"""."""   )

            rename_keys.append((k, k_new)   )
      return rename_keys





def 	_UpperCAmelCase							(  UpperCAmelCase   :      int   ):
      """simple docstring"""




      __lowerCamelCase  :   Tuple							    =    []
      for k in state_dict.keys():
            if k.startswith("""seg_head.aux_head."""   ):
                  keys_to_ignore.append(UpperCAmelCase   )
      for k in keys_to_ignore:
            state_dict.pop(UpperCAmelCase    ,						UpperCAmelCase   )





def 	_UpperCAmelCase							(  ):
      """simple docstring"""




      __lowerCamelCase  :   Optional[int]							    =    "http://images.cocodataset.org/val2017/000000039769.jpg"
      # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg"
      __lowerCamelCase  :   Union[str, Any]							    =    Image.open(requests.get(UpperCAmelCase    ,						stream=UpperCAmelCase   ).raw   )
      return im





@torch.no_grad()
def 	_UpperCAmelCase							(  UpperCAmelCase   :      Dict    ,						UpperCAmelCase   :      Tuple    ,						UpperCAmelCase   :      Optional[Any]    ,						UpperCAmelCase   :      Optional[int]   ):
      """simple docstring"""




      __lowerCamelCase  :   str							    =    get_mobilevitva_config(UpperCAmelCase    ,						UpperCAmelCase   )

      # load original state_dict
      __lowerCamelCase  :   Dict							    =    torch.load(UpperCAmelCase    ,						map_location="""cpu"""   )

      # load huggingface model
      if task_name.startswith("""ade20k_"""   ) or task_name.startswith("""voc_"""   ):
            __lowerCamelCase  :   List[Any]							    =    MobileViTVaForSemanticSegmentation(UpperCAmelCase   ).eval()
            __lowerCamelCase  :   List[str]							    =    False
      else:
            __lowerCamelCase  :   List[str]							    =    MobileViTVaForImageClassification(UpperCAmelCase   ).eval()
            __lowerCamelCase  :   Optional[int]							    =    False

      # remove and rename some keys of load the original model
      __lowerCamelCase  :   Optional[Any]							    =    checkpoint
      remove_unused_keys(UpperCAmelCase   )
      __lowerCamelCase  :   Union[str, Any]							    =    create_rename_keys(UpperCAmelCase    ,						base_model=UpperCAmelCase   )
      for rename_key_src, rename_key_dest in rename_keys:
            rename_key(UpperCAmelCase    ,						UpperCAmelCase    ,						UpperCAmelCase   )

      # load modified state_dict
      model.load_state_dict(UpperCAmelCase   )

      # Check outputs on an image, prepared by MobileViTImageProcessor
      __lowerCamelCase  :   Dict							    =    MobileViTImageProcessor(crop_size=config.image_size    ,						size=config.image_size + 32   )
      __lowerCamelCase  :   Tuple							    =    image_processor(images=prepare_img()    ,						return_tensors="""pt"""   )
      __lowerCamelCase  :   Optional[Any]							    =    model(**UpperCAmelCase   )

      # verify classification model
      if task_name.startswith("""imagenet"""   ):
            __lowerCamelCase  :   List[Any]							    =    outputs.logits
            __lowerCamelCase  :   Any							    =    logits.argmax(-1   ).item()
            print("""Predicted class:"""    ,						model.config.idalabel[predicted_class_idx]   )
            if task_name.startswith("""imagenet1k_256"""   ) and config.width_multiplier == 1.0:
                  # expected_logits for base variant
                  __lowerCamelCase  :   Optional[int]							    =    torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1]   )
                  assert torch.allclose(logits[0, :3]    ,						UpperCAmelCase    ,						atol=1e-4   )

      Path(UpperCAmelCase   ).mkdir(exist_ok=UpperCAmelCase   )
      print(f"""Saving model {task_name} to {pytorch_dump_folder_path}"""   )
      model.save_pretrained(UpperCAmelCase   )
      print(f"""Saving image processor to {pytorch_dump_folder_path}"""   )
      image_processor.save_pretrained(UpperCAmelCase   )


if __name__ == "__main__":
    __UpperCamelCase     :    Any 	=				argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        '--task',
        default='imagenet1k_256',
        type=str,
        help=(
            'Name of the task for which the MobileViTV2 model you\'d like to convert is trained on . '
            '\n                Classification (ImageNet-1k)\n                    - MobileViTV2 (256x256) : imagenet1k_256\n                    - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n                    - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n                      imagenet21k_to_1k_256\n                    - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n                      ImageNet-1k 384x384) : imagenet21k_to_1k_384\n                Segmentation\n                    - ADE20K Dataset : ade20k_deeplabv3\n                    - Pascal VOC 2012 Dataset: voc_deeplabv3\n            '
        ),
        choices=[
            'imagenet1k_256',
            'imagenet1k_384',
            'imagenet21k_to_1k_256',
            'imagenet21k_to_1k_384',
            'ade20k_deeplabv3',
            'voc_deeplabv3',
        ],
    )

    parser.add_argument(
        '--orig_checkpoint_path', required=True, type=str, help='Path to the original state dict (.pt file).'
    )
    parser.add_argument('--orig_config_path', required=True, type=str, help='Path to the original config file.')
    parser.add_argument(
        '--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.'
    )

    __UpperCamelCase     :    Any 	=				parser.parse_args()
    convert_mobilevitva_checkpoint(
        args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path
    )







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
		import PIL


SCREAMING_SNAKE_CASE__     					=			logging.get_logger(__name__)


def     lowercase	(    a     , a ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:Dict				     =						b.T
		SCREAMING_SNAKE_CASE_				:str				     =						np.sum(np.square(a )     , axis=1 )
		SCREAMING_SNAKE_CASE_				:List[Any]				     =						np.sum(np.square(a )     , axis=0 )
		SCREAMING_SNAKE_CASE_				:Optional[int]				     =						np.matmul(a     , a )
		SCREAMING_SNAKE_CASE_				:Any				     =						aa[:, None] - 2 * ab + ba[None, :]
		return d


def     lowercase	(    a     , a ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:str				     =						x.reshape(-1     , 3 )
		SCREAMING_SNAKE_CASE_				:str				     =						squared_euclidean_distance(a     , a )
		return np.argmin(a     , axis=1 )



class 						_UpperCAmelCase      (     lowercase							):
		lowerCamelCase_	:			List[str]       			=  ["""pixel_values"""]






		def __init__(						self				:     Dict   ,  UpperCAmelCase				:     Optional[Union[List[List[int]], np.ndarray]] = None   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     Dict[str, int] = None   ,  UpperCAmelCase				:     PILImageResampling = PILImageResampling.BILINEAR   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     bool = True   ,  **UpperCAmelCase				:     Union[str, Any]   ,  ):
				super().__init__(**UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						size if size is not None else {"height": 2_56, "width": 2_56}
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						get_size_dict(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:int				     =						np.array(UpperCAmelCase) if clusters is not None else None
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						do_resize
				SCREAMING_SNAKE_CASE_				:Dict				     =						size
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						resample
				SCREAMING_SNAKE_CASE_				:Dict				     =						do_normalize
				SCREAMING_SNAKE_CASE_				:Tuple				     =						do_color_quantize






		def _snake_case		(						self				:     Union[str, Any]   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Dict[str, int]   ,  UpperCAmelCase				:     PILImageResampling = PILImageResampling.BILINEAR   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  **UpperCAmelCase				:     List[Any]   ,  ):
				SCREAMING_SNAKE_CASE_				:str				     =						get_size_dict(UpperCAmelCase)
				if "height" not in size or "width" not in size:
						raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}")
				return resize(
				    UpperCAmelCase   ,  size=(size["height"], size["width"])   ,  resample=UpperCAmelCase   ,  data_format=UpperCAmelCase   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     Union[str, Any]   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  ):
				SCREAMING_SNAKE_CASE_				:int				     =						rescale(image=UpperCAmelCase   ,  scale=1 / 127.5   ,  data_format=UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:List[str]				     =						image - 1
				return image







		def _snake_case		(						self				:     List[str]   ,  UpperCAmelCase				:     ImageInput   ,  UpperCAmelCase				:     bool = None   ,  UpperCAmelCase				:     Dict[str, int] = None   ,  UpperCAmelCase				:     PILImageResampling = None   ,  UpperCAmelCase				:     bool = None   ,  UpperCAmelCase				:     Optional[bool] = None   ,  UpperCAmelCase				:     Optional[Union[List[List[int]], np.ndarray]] = None   ,  UpperCAmelCase				:     Optional[Union[str, TensorType]] = None   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST   ,  **UpperCAmelCase				:     Optional[Any]   ,  ):
				SCREAMING_SNAKE_CASE_				:Any				     =						do_resize if do_resize is not None else self.do_resize
				SCREAMING_SNAKE_CASE_				:Dict				     =						size if size is not None else self.size
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						get_size_dict(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						resample if resample is not None else self.resample
				SCREAMING_SNAKE_CASE_				:Dict				     =						do_normalize if do_normalize is not None else self.do_normalize
				SCREAMING_SNAKE_CASE_				:List[str]				     =						do_color_quantize if do_color_quantize is not None else self.do_color_quantize
				SCREAMING_SNAKE_CASE_				:Tuple				     =						clusters if clusters is not None else self.clusters
				SCREAMING_SNAKE_CASE_				:Tuple				     =						np.array(UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Dict				     =						make_list_of_images(UpperCAmelCase)

				if not valid_images(UpperCAmelCase):
						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 or resample is None:
						raise ValueError("Size and resample must be specified if do_resize is True.")

				if do_color_quantize and clusters is None:
						raise ValueError("Clusters must be specified if do_color_quantize is True.")

				# All transformations expect numpy arrays.
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						[to_numpy_array(UpperCAmelCase) for image in images]

				if do_resize:
						SCREAMING_SNAKE_CASE_				:Tuple				     =						[self.resize(image=UpperCAmelCase   ,  size=UpperCAmelCase   ,  resample=UpperCAmelCase) for image in images]

				if do_normalize:
						SCREAMING_SNAKE_CASE_				:int				     =						[self.normalize(image=UpperCAmelCase) for image in images]

				if do_color_quantize:
						SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						[to_channel_dimension_format(UpperCAmelCase   ,  ChannelDimension.LAST) for image in images]
						# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						np.array(UpperCAmelCase)
						SCREAMING_SNAKE_CASE_				:Tuple				     =						color_quantize(UpperCAmelCase   ,  UpperCAmelCase).reshape(images.shape[:-1])

						# flatten to (batch_size, height*width)
						SCREAMING_SNAKE_CASE_				:Any				     =						images.shape[0]
						SCREAMING_SNAKE_CASE_				:Dict				     =						images.reshape(UpperCAmelCase   ,  -1)

						# We need to convert back to a list of images to keep consistent behaviour across processors.
						SCREAMING_SNAKE_CASE_				:Any				     =						list(UpperCAmelCase)
				else:
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						[to_channel_dimension_format(UpperCAmelCase   ,  UpperCAmelCase) for image in images]

				SCREAMING_SNAKE_CASE_				:str				     =						{"input_ids": images}
				return BatchFeature(data=UpperCAmelCase   ,  tensor_type=UpperCAmelCase)






