

"""simple docstring"""





import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
_a					 =				logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')

require_version('datasets>=2.0.0', 'To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt')




def     _A    (    UpperCamelCase_	:			Union[str, Any],     UpperCamelCase_	:			str,     UpperCamelCase_	:			List[Any]=0)      ->		Any:
   '''simple docstring'''


   __lowercase								=		(size, size) if isinstance(UpperCamelCase_,     UpperCamelCase_) else size
   __lowercase						,__lowercase								=		img.size
   __lowercase								=		size[1] - original_height if original_height < size[1] else 0
   __lowercase								=		size[0] - original_width if original_width < size[0] else 0
   __lowercase								=		functional.pad(UpperCamelCase_,     (0, 0, pad_width, pad_height),     fill=UpperCamelCase_)
   return img




class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Any,   UpperCAmelCase__				:     List[str]      ):
    __lowercase								=		transforms



 def __call__(     self				:     Optional[Any],   UpperCAmelCase__				:     Union[str, Any],   UpperCAmelCase__				:     List[str]      ):
    for t in self.transforms:
       __lowercase						,__lowercase								=		t(UpperCAmelCase__,   UpperCAmelCase__      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Union[str, Any]      ):
    pass



 def __call__(     self				:     Any,   UpperCAmelCase__				:     Union[str, Any],   UpperCAmelCase__				:     int      ):
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Any,   UpperCAmelCase__				:     List[Any]      ):
    __lowercase								=		size



 def __call__(     self				:     str,   UpperCAmelCase__				:     Dict,   UpperCAmelCase__				:     Dict      ):
    __lowercase								=		functional.resize(UpperCAmelCase__,   self.size      )
    __lowercase								=		functional.resize(UpperCAmelCase__,   self.size,   interpolation=transforms.InterpolationMode.NEAREST      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Optional[int],   UpperCAmelCase__				:     int,   UpperCAmelCase__				:     Optional[Any]=None      ):
    __lowercase								=		min_size
    if max_size is None:
       __lowercase								=		min_size
    __lowercase								=		max_size



 def __call__(     self				:     Union[str, Any],   UpperCAmelCase__				:     str,   UpperCAmelCase__				:     Optional[Any]      ):
    __lowercase								=		random.randint(self.min_size,   self.max_size      )
    __lowercase								=		functional.resize(UpperCAmelCase__,   UpperCAmelCase__      )
    __lowercase								=		functional.resize(UpperCAmelCase__,   UpperCAmelCase__,   interpolation=transforms.InterpolationMode.NEAREST      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Union[str, Any],   UpperCAmelCase__				:     List[str]      ):
    __lowercase								=		size if isinstance(UpperCAmelCase__,   UpperCAmelCase__      ) else (size, size)



 def __call__(     self				:     Optional[int],   UpperCAmelCase__				:     Any,   UpperCAmelCase__				:     Tuple      ):
    __lowercase								=		pad_if_smaller(UpperCAmelCase__,   self.size      )
    __lowercase								=		pad_if_smaller(UpperCAmelCase__,   self.size,   fill=2_5_5      )
    __lowercase								=		transforms.RandomCrop.get_params(UpperCAmelCase__,   self.size      )
    __lowercase								=		functional.crop(UpperCAmelCase__,   *UpperCAmelCase__      )
    __lowercase								=		functional.crop(UpperCAmelCase__,   *UpperCAmelCase__      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Union[str, Any],   UpperCAmelCase__				:     Optional[Any]      ):
    __lowercase								=		flip_prob



 def __call__(     self				:     Union[str, Any],   UpperCAmelCase__				:     Optional[int],   UpperCAmelCase__				:     Optional[Any]      ):
    if random.random() < self.flip_prob:
       __lowercase								=		functional.hflip(UpperCAmelCase__      )
       __lowercase								=		functional.hflip(UpperCAmelCase__      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __call__(     self				:     Dict,   UpperCAmelCase__				:     List[Any],   UpperCAmelCase__				:     Any      ):
    __lowercase								=		functional.pil_to_tensor(UpperCAmelCase__      )
    __lowercase								=		torch.as_tensor(np.array(UpperCAmelCase__      ),   dtype=torch.intaa      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Tuple,   UpperCAmelCase__				:     List[Any]      ):
    __lowercase								=		dtype



 def __call__(     self				:     str,   UpperCAmelCase__				:     List[Any],   UpperCAmelCase__				:     Tuple      ):
    __lowercase								=		functional.convert_image_dtype(UpperCAmelCase__,   self.dtype      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __init__(     self				:     Tuple,   UpperCAmelCase__				:     Optional[Any],   UpperCAmelCase__				:     Dict      ):
    __lowercase								=		mean
    __lowercase								=		std



 def __call__(     self				:     List[Any],   UpperCAmelCase__				:     Optional[Any],   UpperCAmelCase__				:     Tuple      ):
    __lowercase								=		functional.normalize(UpperCAmelCase__,   mean=self.mean,   std=self.std      )
    return image, target







class    _lowerCAmelCase    :







 """simple docstring"""







 def __call__(     self				:     Tuple,   UpperCAmelCase__				:     List[str],   UpperCAmelCase__				:     Any      ):
    if not isinstance(UpperCAmelCase__,   np.ndarray      ):
       __lowercase								=		np.array(UpperCAmelCase__      ).astype(np.uinta      )
    # avoid using underflow conversion
    __lowercase								=		2_5_5
    __lowercase								=		target - 1
    __lowercase								=		2_5_5

    __lowercase								=		Image.fromarray(UpperCAmelCase__      )
    return image, target







@dataclass
class    _lowerCAmelCase    :







 """simple docstring"""







 __UpperCAmelCase      :   Optional[str]  						=      field(
     default="segments/sidewalk-semantic"	,metadata={
         "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)."
     }	,)
 __UpperCAmelCase      :   Optional[str]  						=      field(
     default=lowercase	,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}  )
 __UpperCAmelCase      :   Optional[float]  						=      field(
     default=0.15	,metadata={"help": "Percent to split off of train for validation."}  )
 __UpperCAmelCase      :   Optional[int]  						=      field(
     default=lowercase	,metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of training examples to this "
             "value if set."
         )
     }	,)
 __UpperCAmelCase      :   Optional[int]  						=      field(
     default=lowercase	,metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
             "value if set."
         )
     }	,)
 __UpperCAmelCase      :   Optional[bool]  						=      field(
     default=lowercase	,metadata={"help": "Whether or not to reduce all labels by 1 and replace background by 255."}	,)


 def    _lowercase					(     self				:     Any      ):
    if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
       raise ValueError(
           "You must specify either a dataset name from the hub or a train and/or validation directory."      )







@dataclass
class    _lowerCAmelCase    :







 """simple docstring"""







 __UpperCAmelCase      :   str  						=      field(
     default="nvidia/mit-b0"	,metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}	,)
 __UpperCAmelCase      :   Optional[str]  						=      field(
     default=lowercase	,metadata={"help": "Pretrained config name or path if not the same as model_name"}  )
 __UpperCAmelCase      :   Optional[str]  						=      field(
     default=lowercase	,metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}  )
 __UpperCAmelCase      :   str  						=      field(
     default="main"	,metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}	,)
 __UpperCAmelCase      :   str  						=      field(default=lowercase	,metadata={"help": "Name or path of preprocessor config."}  )
 __UpperCAmelCase      :   bool  						=      field(
     default=lowercase	,metadata={
         "help": (
             "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
             "with private models)."
         )
     }	,)







def     _A    (    )      ->		str:
   '''simple docstring'''


   __lowercase								=		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
   if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
      # If we pass only one argument to the script and it's the path to a json file,
      # let's parse it to get our arguments.
      __lowercase						,__lowercase						,__lowercase								=		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
   else:
      __lowercase						,__lowercase						,__lowercase								=		parser.parse_args_into_dataclasses()

   # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
   # information sent is the one passed as arguments along with your Python/PyTorch versions.
   send_example_telemetry("run_semantic_segmentation",     UpperCamelCase_,     UpperCamelCase_)

   # Setup logging
   logging.basicConfig(
       format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",     datefmt="%m/%d/%Y %H:%M:%S",     handlers=[logging.StreamHandler(sys.stdout)],     )

   if training_args.should_log:
      # The default of training_args.log_level is passive, so we set log level at info here to have that default.
      transformers.utils.logging.set_verbosity_info()

   __lowercase								=		training_args.get_process_log_level()
   logger.setLevel(UpperCamelCase_)
   transformers.utils.logging.set_verbosity(UpperCamelCase_)
   transformers.utils.logging.enable_default_handler()
   transformers.utils.logging.enable_explicit_format()

   # Log on each process the small summary:
   logger.warning(
       F"""Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"""
       + F"""distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fpaa}""")
   logger.info(F"""Training/evaluation parameters {training_args}""")

   # Detecting last checkpoint.
   __lowercase								=		None
   if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir:
      __lowercase								=		get_last_checkpoint(training_args.output_dir)
      if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0:
         raise ValueError(
             F"""Output directory ({training_args.output_dir}) already exists and is not empty. """
             "Use --overwrite_output_dir to overcome.")
      elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
         logger.info(
             F"""Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change """
             "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.")

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
   __lowercase								=		load_dataset(data_args.dataset_name,     cache_dir=model_args.cache_dir)

   # Rename column names to standardized names (only "image" and "label" need to be present)
   if "pixel_values" in dataset["train"].column_names:
      __lowercase								=		dataset.rename_columns({"pixel_values": "image"})
   if "annotation" in dataset["train"].column_names:
      __lowercase								=		dataset.rename_columns({"annotation": "label"})

   # If we don't have a validation split, split off a percentage of train as validation.
   __lowercase								=		None if "validation" in dataset.keys() else data_args.train_val_split
   if isinstance(data_args.train_val_split,     UpperCamelCase_) and data_args.train_val_split > 0.0:
      __lowercase								=		dataset["train"].train_test_split(data_args.train_val_split)
      __lowercase								=		split["train"]
      __lowercase								=		split["test"]

   # Prepare label mappings.
   # We'll include these in the model's config to get human readable labels in the Inference API.
   if data_args.dataset_name == "scene_parse_150":
      __lowercase								=		"huggingface/label-files"
      __lowercase								=		"ade20k-id2label.json"
   else:
      __lowercase								=		data_args.dataset_name
      __lowercase								=		"id2label.json"
   __lowercase								=		json.load(open(hf_hub_download(UpperCamelCase_,     UpperCamelCase_,     repo_type="dataset"),     "r"))
   __lowercase								=		{int(UpperCamelCase_): v for k, v in idalabel.items()}
   __lowercase								=		{v: str(UpperCamelCase_) for k, v in idalabel.items()}

   # Load the mean IoU metric from the datasets package
   __lowercase								=		evaluate.load("mean_iou")

   # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
   # predictions and label_ids field) and has to return a dictionary string to float.
   @torch.no_grad()
   def compute_metrics(UpperCamelCase_	:			Optional[Any]):
      __lowercase						,__lowercase								=		eval_pred
      __lowercase								=		torch.from_numpy(UpperCamelCase_)
      # scale the logits to the size of the label
      __lowercase								=		nn.functional.interpolate(
          UpperCamelCase_,     size=labels.shape[-2:],     mode="bilinear",     align_corners=UpperCamelCase_,     ).argmax(dim=1)

      __lowercase								=		logits_tensor.detach().cpu().numpy()
      __lowercase								=		metric.compute(
          predictions=UpperCamelCase_,     references=UpperCamelCase_,     num_labels=len(UpperCamelCase_),     ignore_index=0,     reduce_labels=image_processor.do_reduce_labels,     )
      # add per category metrics as individual key-value pairs
      __lowercase								=		metrics.pop("per_category_accuracy").tolist()
      __lowercase								=		metrics.pop("per_category_iou").tolist()

      metrics.update({F"""accuracy_{idalabel[i]}""": v for i, v in enumerate(UpperCamelCase_)})
      metrics.update({F"""iou_{idalabel[i]}""": v for i, v in enumerate(UpperCamelCase_)})

      return metrics

   __lowercase								=		AutoConfig.from_pretrained(
       model_args.config_name or model_args.model_name_or_path,     labelaid=UpperCamelCase_,     idalabel=UpperCamelCase_,     cache_dir=model_args.cache_dir,     revision=model_args.model_revision,     use_auth_token=True if model_args.use_auth_token else None,     )
   __lowercase								=		AutoModelForSemanticSegmentation.from_pretrained(
       model_args.model_name_or_path,     from_tf=bool(".ckpt" in model_args.model_name_or_path),     config=UpperCamelCase_,     cache_dir=model_args.cache_dir,     revision=model_args.model_revision,     use_auth_token=True if model_args.use_auth_token else None,     )
   __lowercase								=		AutoImageProcessor.from_pretrained(
       model_args.image_processor_name or model_args.model_name_or_path,     cache_dir=model_args.cache_dir,     revision=model_args.model_revision,     use_auth_token=True if model_args.use_auth_token else None,     )

   # Define torchvision transforms to be applied to each image + target.
   # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
   # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
   if "shortest_edge" in image_processor.size:
      # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
      __lowercase								=		(image_processor.size["shortest_edge"], image_processor.size["shortest_edge"])
   else:
      __lowercase								=		(image_processor.size["height"], image_processor.size["width"])
   __lowercase								=		Compose(
       [
           ReduceLabels() if data_args.reduce_labels else Identity(),
           RandomCrop(size=UpperCamelCase_),
           RandomHorizontalFlip(flip_prob=0.5),
           PILToTensor(),
           ConvertImageDtype(torch.float),
           Normalize(mean=image_processor.image_mean,     std=image_processor.image_std),
       ])
   # Define torchvision transform to be applied to each image.
   # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
   __lowercase								=		Compose(
       [
           ReduceLabels() if data_args.reduce_labels else Identity(),
           Resize(size=UpperCamelCase_),
           PILToTensor(),
           ConvertImageDtype(torch.float),
           Normalize(mean=image_processor.image_mean,     std=image_processor.image_std),
       ])

   def preprocess_train(UpperCamelCase_	:			List[Any]):
      __lowercase								=		[]
      __lowercase								=		[]
      for image, target in zip(example_batch["image"],     example_batch["label"]):
         __lowercase						,__lowercase								=		train_transforms(image.convert("RGB"),     UpperCamelCase_)
         pixel_values.append(UpperCamelCase_)
         labels.append(UpperCamelCase_)

      __lowercase								=		{}
      __lowercase								=		torch.stack(UpperCamelCase_)
      __lowercase								=		torch.stack(UpperCamelCase_)

      return encoding

   def preprocess_val(UpperCamelCase_	:			Tuple):
      __lowercase								=		[]
      __lowercase								=		[]
      for image, target in zip(example_batch["image"],     example_batch["label"]):
         __lowercase						,__lowercase								=		val_transforms(image.convert("RGB"),     UpperCamelCase_)
         pixel_values.append(UpperCamelCase_)
         labels.append(UpperCamelCase_)

      __lowercase								=		{}
      __lowercase								=		torch.stack(UpperCamelCase_)
      __lowercase								=		torch.stack(UpperCamelCase_)

      return encoding

   if training_args.do_train:
      if "train" not in dataset:
         raise ValueError("--do_train requires a train dataset")
      if data_args.max_train_samples is not None:
         __lowercase								=		(
             dataset["train"].shuffle(seed=training_args.seed).select(range(data_args.max_train_samples))
         )
      # Set the training transforms
      dataset["train"].set_transform(UpperCamelCase_)

   if training_args.do_eval:
      if "validation" not in dataset:
         raise ValueError("--do_eval requires a validation dataset")
      if data_args.max_eval_samples is not None:
         __lowercase								=		(
             dataset["validation"].shuffle(seed=training_args.seed).select(range(data_args.max_eval_samples))
         )
      # Set the validation transforms
      dataset["validation"].set_transform(UpperCamelCase_)

   # Initalize our trainer
   __lowercase								=		Trainer(
       model=UpperCamelCase_,     args=UpperCamelCase_,     train_dataset=dataset["train"] if training_args.do_train else None,     eval_dataset=dataset["validation"] if training_args.do_eval else None,     compute_metrics=UpperCamelCase_,     tokenizer=UpperCamelCase_,     data_collator=UpperCamelCase_,     )

   # Training
   if training_args.do_train:
      __lowercase								=		None
      if training_args.resume_from_checkpoint is not None:
         __lowercase								=		training_args.resume_from_checkpoint
      elif last_checkpoint is not None:
         __lowercase								=		last_checkpoint
      __lowercase								=		trainer.train(resume_from_checkpoint=UpperCamelCase_)
      trainer.save_model()
      trainer.log_metrics("train",     train_result.metrics)
      trainer.save_metrics("train",     train_result.metrics)
      trainer.save_state()

   # Evaluation
   if training_args.do_eval:
      __lowercase								=		trainer.evaluate()
      trainer.log_metrics("eval",     UpperCamelCase_)
      trainer.save_metrics("eval",     UpperCamelCase_)

   # Write model card and (optionally) push to hub
   __lowercase								=		{
       "finetuned_from": model_args.model_name_or_path,
       "dataset": data_args.dataset_name,
       "tags": ["image-segmentation", "vision"],
   }
   if training_args.push_to_hub:
      trainer.push_to_hub(**UpperCamelCase_)
   else:
      trainer.create_model_card(**UpperCamelCase_)


if __name__ == "__main__":
   main()







"""simple docstring"""





import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import OwlViTImageProcessor




class    _lowerCAmelCase    (      unittest.TestCase  ):







 """simple docstring"""







 def __init__(     self				:     Union[str, Any],   UpperCAmelCase__				:     Dict,   UpperCAmelCase__				:     Optional[int]=7,   UpperCAmelCase__				:     List[str]=3,   UpperCAmelCase__				:     List[Any]=1_8,   UpperCAmelCase__				:     Any=3_0,   UpperCAmelCase__				:     str=4_0_0,   UpperCAmelCase__				:     Union[str, Any]=True,   UpperCAmelCase__				:     Dict=None,   UpperCAmelCase__				:     int=True,   UpperCAmelCase__				:     str=None,   UpperCAmelCase__				:     Dict=True,   UpperCAmelCase__				:     str=[0.48_145_466, 0.4_578_275, 0.40_821_073],   UpperCAmelCase__				:     Dict=[0.26_862_954, 0.26_130_258, 0.27_577_711],   UpperCAmelCase__				:     Any=True,   ):
    __lowercase								=		parent
    __lowercase								=		batch_size
    __lowercase								=		num_channels
    __lowercase								=		image_size
    __lowercase								=		min_resolution
    __lowercase								=		max_resolution
    __lowercase								=		do_resize
    __lowercase								=		size if size is not None else {"height": 1_8, "width": 1_8}
    __lowercase								=		do_center_crop
    __lowercase								=		crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
    __lowercase								=		do_normalize
    __lowercase								=		image_mean
    __lowercase								=		image_std
    __lowercase								=		do_convert_rgb



 def    _lowercase					(     self				:     List[str]      ):
    return {
        "do_resize": self.do_resize,
        "size": self.size,
        "do_center_crop": self.do_center_crop,
        "crop_size": self.crop_size,
        "do_normalize": self.do_normalize,
        "image_mean": self.image_mean,
        "image_std": self.image_std,
        "do_convert_rgb": self.do_convert_rgb,
    }







@require_torch
@require_vision
class    _lowerCAmelCase    (      lowercase	,unittest.TestCase  ):







 """simple docstring"""







 __UpperCAmelCase      :   List[str]  						=      OwlViTImageProcessor if is_vision_available() else None


 def    _lowercase					(     self				:     Dict      ):
    __lowercase								=		OwlViTImageProcessingTester(self      )


 @property
 def    _lowercase					(     self				:     int      ):
    return self.image_processor_tester.prepare_image_processor_dict()


 def    _lowercase					(     self				:     Tuple      ):
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_resize"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "size"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_center_crop"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "center_crop"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_normalize"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "image_mean"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "image_std"      )      )
    self.assertTrue(hasattr(UpperCAmelCase__,   "do_convert_rgb"      )      )


 def    _lowercase					(     self				:     Dict      ):
    __lowercase								=		self.image_processing_class.from_dict(self.image_processor_dict      )
    self.assertEqual(image_processor.size,   {"height": 1_8, "width": 1_8}      )
    self.assertEqual(image_processor.crop_size,   {"height": 1_8, "width": 1_8}      )

    __lowercase								=		self.image_processing_class.from_dict(self.image_processor_dict,   size=4_2,   crop_size=8_4      )
    self.assertEqual(image_processor.size,   {"height": 4_2, "width": 4_2}      )
    self.assertEqual(image_processor.crop_size,   {"height": 8_4, "width": 8_4}      )


 def    _lowercase					(     self				:     Any      ):
    # Initialize image_processing
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    # create random PIL images
    __lowercase								=		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								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )

    # Test batched
    __lowercase								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )


 def    _lowercase					(     self				:     Optional[Any]      ):
    # Initialize image_processing
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    # create random numpy tensors
    __lowercase								=		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								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )

    # Test batched
    __lowercase								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )



 def    _lowercase					(     self				:     List[str]      ):
    # Initialize image_processing
    __lowercase								=		self.image_processing_class(**self.image_processor_dict      )
    # create random PyTorch tensors
    __lowercase								=		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								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )

    # Test batched
    __lowercase								=		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.crop_size["height"],
            self.image_processor_tester.crop_size["width"],
        ),   )




