




'''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
lowerCAmelCase_			:     List[str]							    =     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    _SCREAMING_SNAKE_CASE    (			UpperCamelCase__						:				str   ,						UpperCamelCase__						:				int   ,						UpperCamelCase__						:				Tuple=0							):




     """simple docstring"""


     a_    :       Optional[Any]    	=     (size, size) if isinstance(UpperCamelCase__   ,						UpperCamelCase__							) else size
     a_	,    a_    :       str    	=     img.size
     a_    :       Dict    	=     size[1] - original_height if original_height < size[1] else 0
     a_    :       int    	=     size[0] - original_width if original_width < size[0] else 0
     a_    :       List[str]    	=     functional.pad(UpperCamelCase__   ,						(0, 0, pad_width, pad_height)   ,						fill=UpperCamelCase__							)
     return img







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Union[str, Any]	,	lowercase__      :     Optional[int]					):


           '''simple docstring'''

           a_    :       List[str]    	=     transforms






      def __call__(   self      :     Tuple	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Tuple					):


           '''simple docstring'''

           for t in self.transforms:
                a_	,    a_    :       Any    	=     t(lowercase__	,	lowercase__					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Optional[int]					):


           '''simple docstring'''

           pass






      def __call__(   self      :     Any	,	lowercase__      :     Any	,	lowercase__      :     str					):


           '''simple docstring'''

           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Optional[int]	,	lowercase__      :     Optional[Any]					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     size






      def __call__(   self      :     Optional[int]	,	lowercase__      :     Tuple	,	lowercase__      :     Union[str, Any]					):


           '''simple docstring'''

           a_    :       List[str]    	=     functional.resize(lowercase__	,	self.size					)
           a_    :       List[Any]    	=     functional.resize(lowercase__	,	self.size	,	interpolation=transforms.InterpolationMode.NEAREST					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     str	,	lowercase__      :     List[str]	,	lowercase__      :     Optional[Any]=None					):


           '''simple docstring'''

           a_    :       Any    	=     min_size
           if max_size is None:
                a_    :       Optional[int]    	=     min_size
           a_    :       Optional[int]    	=     max_size






      def __call__(   self      :     Any	,	lowercase__      :     Dict	,	lowercase__      :     Any					):


           '''simple docstring'''

           a_    :       Tuple    	=     random.randint(self.min_size	,	self.max_size					)
           a_    :       Dict    	=     functional.resize(lowercase__	,	lowercase__					)
           a_    :       int    	=     functional.resize(lowercase__	,	lowercase__	,	interpolation=transforms.InterpolationMode.NEAREST					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Tuple	,	lowercase__      :     Dict					):


           '''simple docstring'''

           a_    :       Dict    	=     size if isinstance(lowercase__	,	lowercase__					) else (size, size)






      def __call__(   self      :     List[str]	,	lowercase__      :     Optional[Any]	,	lowercase__      :     Optional[int]					):


           '''simple docstring'''

           a_    :       Optional[int]    	=     pad_if_smaller(lowercase__	,	self.size					)
           a_    :       Union[str, Any]    	=     pad_if_smaller(lowercase__	,	self.size	,	fill=255					)
           a_    :       Dict    	=     transforms.RandomCrop.get_params(lowercase__	,	self.size					)
           a_    :       Dict    	=     functional.crop(lowercase__	,	*lowercase__					)
           a_    :       Any    	=     functional.crop(lowercase__	,	*lowercase__					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






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


           '''simple docstring'''

           a_    :       Dict    	=     flip_prob






      def __call__(   self      :     List[Any]	,	lowercase__      :     Any	,	lowercase__      :     Union[str, Any]					):


           '''simple docstring'''

           if random.random() < self.flip_prob:
                a_    :       Dict    	=     functional.hflip(lowercase__					)
                a_    :       Optional[int]    	=     functional.hflip(lowercase__					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __call__(   self      :     List[Any]	,	lowercase__      :     Any	,	lowercase__      :     Optional[int]					):


           '''simple docstring'''

           a_    :       int    	=     functional.pil_to_tensor(lowercase__					)
           a_    :       List[Any]    	=     torch.as_tensor(np.array(lowercase__					)	,	dtype=torch.intaa					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __init__(   self      :     Optional[Any]	,	lowercase__      :     str					):


           '''simple docstring'''

           a_    :       List[str]    	=     dtype






      def __call__(   self      :     Any	,	lowercase__      :     Dict	,	lowercase__      :     Optional[Any]					):


           '''simple docstring'''

           a_    :       Any    	=     functional.convert_image_dtype(lowercase__	,	self.dtype					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






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


           '''simple docstring'''

           a_    :       Optional[int]    	=     mean
           a_    :       List[Any]    	=     std






      def __call__(   self      :     List[str]	,	lowercase__      :     List[str]	,	lowercase__      :     Union[str, Any]					):


           '''simple docstring'''

           a_    :       Any    	=     functional.normalize(lowercase__	,	mean=self.mean	,	std=self.std					)
           return image, target







class     SCREAMING_SNAKE_CASE						:






      def __call__(   self      :     Tuple	,	lowercase__      :     Optional[int]	,	lowercase__      :     Tuple					):


           '''simple docstring'''

           if not isinstance(lowercase__	,	np.ndarray					):
                a_    :       Any    	=     np.array(lowercase__					).astype(np.uinta					)
           # avoid using underflow conversion
           a_    :       int    	=     255
           a_    :       Optional[Any]    	=     target - 1
           a_    :       Dict    	=     255

           a_    :       Tuple    	=     Image.fromarray(lowercase__					)
           return image, target







@dataclass
class     SCREAMING_SNAKE_CASE						:
      __magic_name__     :					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).'''
          }       ,			)
      __magic_name__     :					Optional[str]             =				field(
          default=snake_case_       ,			metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}							)
      __magic_name__     :					Optional[float]             =				field(
          default=0.15       ,			metadata={'''help''': '''Percent to split off of train for validation.'''}							)
      __magic_name__     :					Optional[int]             =				field(
          default=snake_case_       ,			metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                  '''value if set.'''
              )
          }       ,			)
      __magic_name__     :					Optional[int]             =				field(
          default=snake_case_       ,			metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                  '''value if set.'''
              )
          }       ,			)
      __magic_name__     :					Optional[bool]             =				field(
          default=snake_case_       ,			metadata={'''help''': '''Whether or not to reduce all labels by 1 and replace background by 255.'''}       ,			)






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

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



def    _SCREAMING_SNAKE_CASE    (			):




     """simple docstring"""


     a_    :       Tuple    	=     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.
          a_	,    a_	,    a_    :       Optional[Any]    	=     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
     else:
          a_	,    a_	,    a_    :       Optional[Any]    	=     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()

     a_    :       Optional[int]    	=     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.
     a_    :       Tuple    	=     None
     if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
          a_    :       Tuple    	=     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
     a_    :       Optional[Any]    	=     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:
          a_    :       Any    	=     dataset.rename_columns({"""pixel_values""": """image"""}							)
     if "annotation" in dataset["train"].column_names:
          a_    :       int    	=     dataset.rename_columns({"""annotation""": """label"""}							)

     # If we don't have a validation split, split off a percentage of train as validation.
     a_    :       Optional[Any]    	=     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:
          a_    :       Optional[Any]    	=     dataset["""train"""].train_test_split(data_args.train_val_split							)
          a_    :       List[str]    	=     split["""train"""]
          a_    :       int    	=     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":
          a_    :       Dict    	=     """huggingface/label-files"""
          a_    :       List[Any]    	=     """ade20k-id2label.json"""
     else:
          a_    :       Union[str, Any]    	=     data_args.dataset_name
          a_    :       Dict    	=     """id2label.json"""
     a_    :       List[str]    	=     json.load(open(hf_hub_download(UpperCamelCase__   ,						UpperCamelCase__   ,						repo_type="""dataset"""							)   ,						"""r"""							)							)
     a_    :       List[str]    	=     {int(UpperCamelCase__							): v for k, v in idalabel.items()}
     a_    :       Optional[int]    	=     {v: str(UpperCamelCase__							) for k, v in idalabel.items()}

     # Load the mean IoU metric from the datasets package
     a_    :       Any    	=     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__						:				Union[str, Any]							):
          a_	,    a_    :       int    	=     eval_pred
          a_    :       Any    	=     torch.from_numpy(UpperCamelCase__							)
          # scale the logits to the size of the label
          a_    :       List[str]    	=     nn.functional.interpolate(
              UpperCamelCase__   ,						size=labels.shape[-2:]   ,						mode="""bilinear"""   ,						align_corners=UpperCamelCase__   ,						).argmax(dim=1							)

          a_    :       Any    	=     logits_tensor.detach().cpu().numpy()
          a_    :       List[Any]    	=     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
          a_    :       List[Any]    	=     metrics.pop("""per_category_accuracy"""							).tolist()
          a_    :       str    	=     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

     a_    :       Tuple    	=     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   ,						)
     a_    :       Dict    	=     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   ,						)
     a_    :       Dict    	=     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.
          a_    :       int    	=     (image_processor.size["""shortest_edge"""], image_processor.size["""shortest_edge"""])
     else:
          a_    :       Dict    	=     (image_processor.size["""height"""], image_processor.size["""width"""])
     a_    :       Any    	=     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)
     a_    :       Tuple    	=     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[str]							):
          a_    :       str    	=     []
          a_    :       Optional[int]    	=     []
          for image, target in zip(example_batch["""image"""]   ,						example_batch["""label"""]							):
               a_	,    a_    :       Any    	=     train_transforms(image.convert("""RGB"""							)   ,						UpperCamelCase__							)
               pixel_values.append(UpperCamelCase__							)
               labels.append(UpperCamelCase__							)

          a_    :       str    	=     {}
          a_    :       List[str]    	=     torch.stack(UpperCamelCase__							)
          a_    :       Union[str, Any]    	=     torch.stack(UpperCamelCase__							)

          return encoding

     def preprocess_val(UpperCamelCase__						:				int							):
          a_    :       Any    	=     []
          a_    :       Optional[Any]    	=     []
          for image, target in zip(example_batch["""image"""]   ,						example_batch["""label"""]							):
               a_	,    a_    :       List[Any]    	=     val_transforms(image.convert("""RGB"""							)   ,						UpperCamelCase__							)
               pixel_values.append(UpperCamelCase__							)
               labels.append(UpperCamelCase__							)

          a_    :       List[str]    	=     {}
          a_    :       Tuple    	=     torch.stack(UpperCamelCase__							)
          a_    :       Dict    	=     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:
               a_    :       Union[str, Any]    	=     (
                   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:
               a_    :       Any    	=     (
                   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
     a_    :       Optional[int]    	=     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:
          a_    :       Union[str, Any]    	=     None
          if training_args.resume_from_checkpoint is not None:
               a_    :       Union[str, Any]    	=     training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               a_    :       Union[str, Any]    	=     last_checkpoint
          a_    :       List[Any]    	=     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:
          a_    :       List[str]    	=     trainer.evaluate()
          trainer.log_metrics("""eval"""   ,						UpperCamelCase__							)
          trainer.save_metrics("""eval"""   ,						UpperCamelCase__							)

     # Write model card and (optionally) push to hub
     a_    :       int    	=     {
         """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


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import CLIPImageProcessor







class     SCREAMING_SNAKE_CASE						(	unittest.TestCase							):






      def __init__(   self      :     Tuple	,	lowercase__      :     Union[str, Any]	,	lowercase__      :     Optional[Any]=7	,	lowercase__      :     str=3	,	lowercase__      :     Tuple=18	,	lowercase__      :     Dict=30	,	lowercase__      :     List[Any]=400	,	lowercase__      :     Optional[Any]=True	,	lowercase__      :     Union[str, Any]=None	,	lowercase__      :     Union[str, Any]=True	,	lowercase__      :     Tuple=None	,	lowercase__      :     str=True	,	lowercase__      :     List[Any]=[0.48145466, 0.4578275, 0.40821073]	,	lowercase__      :     Optional[Any]=[0.26862954, 0.26130258, 0.27577711]	,	lowercase__      :     str=True	,	):


           '''simple docstring'''

           a_    :       Dict    	=     size if size is not None else {"""shortest_edge""": 20}
           a_    :       Any    	=     crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
           a_    :       List[str]    	=     parent
           a_    :       Dict    	=     batch_size
           a_    :       Any    	=     num_channels
           a_    :       Optional[int]    	=     image_size
           a_    :       Union[str, Any]    	=     min_resolution
           a_    :       Tuple    	=     max_resolution
           a_    :       int    	=     do_resize
           a_    :       List[str]    	=     size
           a_    :       Optional[int]    	=     do_center_crop
           a_    :       str    	=     crop_size
           a_    :       str    	=     do_normalize
           a_    :       Any    	=     image_mean
           a_    :       List[str]    	=     image_std
           a_    :       Any    	=     do_convert_rgb






      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           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,
           }






      def        lowercase_	(   self      :     str	,	lowercase__      :     Union[str, Any]=False	,	lowercase__      :     Union[str, Any]=False	,	lowercase__      :     Union[str, Any]=False					):


           '''simple docstring'''

           assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

           if equal_resolution:
                a_    :       Union[str, Any]    	=     []
                for i in range(self.batch_size					):
                     image_inputs.append(
                         np.random.randint(
                             255	,	size=(self.num_channels, self.max_resolution, self.max_resolution)	,	dtype=np.uinta					)					)
           else:
                a_    :       int    	=     []
                for i in range(self.batch_size					):
                     a_	,    a_    :       Any    	=     np.random.choice(np.arange(self.min_resolution	,	self.max_resolution					)	,	2					)
                     image_inputs.append(np.random.randint(255	,	size=(self.num_channels, width, height)	,	dtype=np.uinta					)					)

           if not numpify and not torchify:
                # PIL expects the channel dimension as last dimension
                a_    :       Union[str, Any]    	=     [Image.fromarray(np.moveaxis(lowercase__	,	0	,	-1					)					) for x in image_inputs]

           if torchify:
                a_    :       List[Any]    	=     [torch.from_numpy(lowercase__					) for x in image_inputs]

           return image_inputs







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					int             =				CLIPImageProcessor if is_vision_available() else None






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           a_    :       Dict    	=     CLIPImageProcessingTester(self					)






      @property
      def        lowercase_	(   self      :     Optional[int]					):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def        lowercase_	(   self      :     Optional[Any]					):


           '''simple docstring'''

           a_    :       List[Any]    	=     self.image_processing_class(**self.image_processor_dict					)
           self.assertTrue(hasattr(lowercase__	,	"""do_resize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""size"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_normalize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_mean"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_std"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_convert_rgb"""					)					)






      def        lowercase_	(   self      :     Dict					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     self.image_processing_class.from_dict(self.image_processor_dict					)
           self.assertEqual(image_processor.size	,	{"""shortest_edge""": 20}					)
           self.assertEqual(image_processor.crop_size	,	{"""height""": 18, """width""": 18}					)

           a_    :       Optional[int]    	=     self.image_processing_class.from_dict(self.image_processor_dict	,	size=42	,	crop_size=84					)
           self.assertEqual(image_processor.size	,	{"""shortest_edge""": 42}					)
           self.assertEqual(image_processor.crop_size	,	{"""height""": 84, """width""": 84}					)






      def        lowercase_	(   self      :     List[str]					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

           a_    :       str    	=     self.image_processing_class(**self.image_processor_dict					)
           # create random PIL images
           a_    :       str    	=     self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__					)
           for image in image_inputs:
                self.assertIsInstance(lowercase__	,	Image.Image					)

           # Test not batched input
           a_    :       Optional[Any]    	=     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
           a_    :       str    	=     image_processing(lowercase__	,	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      :     Tuple					):


           '''simple docstring'''

           a_    :       Optional[Any]    	=     self.image_processing_class(**self.image_processor_dict					)
           # create random numpy tensors
           a_    :       Optional[int]    	=     self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__	,	numpify=lowercase__					)
           for image in image_inputs:
                self.assertIsInstance(lowercase__	,	np.ndarray					)

           # Test not batched input
           a_    :       Tuple    	=     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
           a_    :       str    	=     image_processing(lowercase__	,	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      :     str					):


           '''simple docstring'''

           a_    :       Dict    	=     self.image_processing_class(**self.image_processor_dict					)
           # create random PyTorch tensors
           a_    :       Optional[int]    	=     self.image_processor_tester.prepare_inputs(equal_resolution=lowercase__	,	torchify=lowercase__					)
           for image in image_inputs:
                self.assertIsInstance(lowercase__	,	torch.Tensor					)

           # Test not batched input
           a_    :       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.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)

           # Test batched
           a_    :       int    	=     image_processing(lowercase__	,	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"""],
               )	,	)







@require_torch
@require_vision
class     SCREAMING_SNAKE_CASE						(	snake_case_       ,			unittest.TestCase							):
      __magic_name__     :					List[str]             =				CLIPImageProcessor if is_vision_available() else None






      def        lowercase_	(   self      :     str					):


           '''simple docstring'''

           a_    :       str    	=     CLIPImageProcessingTester(self	,	num_channels=4					)
           a_    :       Dict    	=     3






      @property
      def        lowercase_	(   self      :     Any					):


           '''simple docstring'''

           return self.image_processor_tester.prepare_image_processor_dict()






      def        lowercase_	(   self      :     List[Any]					):


           '''simple docstring'''

           a_    :       int    	=     self.image_processing_class(**self.image_processor_dict					)
           self.assertTrue(hasattr(lowercase__	,	"""do_resize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""size"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""center_crop"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_normalize"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_mean"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""image_std"""					)					)
           self.assertTrue(hasattr(lowercase__	,	"""do_convert_rgb"""					)					)






      def        lowercase_	(   self      :     int					):


           '''simple docstring'''

           pass






      def        lowercase_	(   self      :     Tuple					):


           '''simple docstring'''

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

           # Test not batched input
           a_    :       Optional[Any]    	=     image_processing(image_inputs[0]	,	return_tensors="""pt"""					).pixel_values
           self.assertEqual(
               encoded_images.shape	,	(
                   1,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)

           # Test batched
           a_    :       List[str]    	=     image_processing(lowercase__	,	return_tensors="""pt"""					).pixel_values
           self.assertEqual(
               encoded_images.shape	,	(
                   self.image_processor_tester.batch_size,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.crop_size["""height"""],
                   self.image_processor_tester.crop_size["""width"""],
               )	,	)
