






'''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
UpperCamelCase__	=     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  ,						_UpperCamelCase  ,						_UpperCamelCase=0							):


   """simple docstring"""




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


class     _UpperCAmelCase  :




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






       '''simple docstring'''






       lowercase_		:      Dict          =       transforms





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






       '''simple docstring'''






       for t in self.transforms:
          lowercase_      ,						lowercase_		:      Optional[Any]          =       t(a					,       a     )
       return image, target


class     _UpperCAmelCase  :




    def __init__(     self					:    Dict     ):






       '''simple docstring'''






       pass





    def __call__(     self					:    Tuple					,       a					:    List[str]					,       a					:    Optional[Any]     ):






       '''simple docstring'''






       return image, target


class     _UpperCAmelCase  :




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






       '''simple docstring'''






       lowercase_		:      List[Any]          =       size





    def __call__(     self					:    int					,       a					:    int					,       a					:    Dict     ):






       '''simple docstring'''






       lowercase_		:      Tuple          =       functional.resize(a					,       self.size     )
       lowercase_		:      Dict          =       functional.resize(a					,       self.size					,       interpolation=transforms.InterpolationMode.NEAREST     )
       return image, target


class     _UpperCAmelCase  :




    def __init__(     self					:    Any					,       a					:    str					,       a					:    Tuple=None     ):






       '''simple docstring'''






       lowercase_		:      Any          =       min_size
       if max_size is None:
          lowercase_		:      Optional[Any]          =       min_size
       lowercase_		:      Union[str, Any]          =       max_size





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






       '''simple docstring'''






       lowercase_		:      Any          =       random.randint(self.min_size					,       self.max_size     )
       lowercase_		:      Any          =       functional.resize(a					,       a     )
       lowercase_		:      Optional[int]          =       functional.resize(a					,       a					,       interpolation=transforms.InterpolationMode.NEAREST     )
       return image, target


class     _UpperCAmelCase  :




    def __init__(     self					:    Any					,       a					:    Any     ):






       '''simple docstring'''






       lowercase_		:      str          =       size if isinstance(a					,       a     ) else (size, size)





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






       '''simple docstring'''






       lowercase_		:      str          =       pad_if_smaller(a					,       self.size     )
       lowercase_		:      str          =       pad_if_smaller(a					,       self.size					,       fill=2_5_5     )
       lowercase_		:      List[str]          =       transforms.RandomCrop.get_params(a					,       self.size     )
       lowercase_		:      Any          =       functional.crop(a					,       *a     )
       lowercase_		:      int          =       functional.crop(a					,       *a     )
       return image, target


class     _UpperCAmelCase  :




    def __init__(     self					:    List[Any]					,       a					:    Any     ):






       '''simple docstring'''






       lowercase_		:      Any          =       flip_prob





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






       '''simple docstring'''






       if random.random() < self.flip_prob:
          lowercase_		:      List[str]          =       functional.hflip(a     )
          lowercase_		:      Tuple          =       functional.hflip(a     )
       return image, target


class     _UpperCAmelCase  :




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






       '''simple docstring'''






       lowercase_		:      Any          =       functional.pil_to_tensor(a     )
       lowercase_		:      Union[str, Any]          =       torch.as_tensor(np.array(a     )					,       dtype=torch.intaa     )
       return image, target


class     _UpperCAmelCase  :




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






       '''simple docstring'''






       lowercase_		:      Tuple          =       dtype





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






       '''simple docstring'''






       lowercase_		:      Dict          =       functional.convert_image_dtype(a					,       self.dtype     )
       return image, target


class     _UpperCAmelCase  :




    def __init__(     self					:    Optional[int]					,       a					:    Optional[Any]					,       a					:    List[str]     ):






       '''simple docstring'''






       lowercase_		:      Optional[int]          =       mean
       lowercase_		:      Tuple          =       std





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






       '''simple docstring'''






       lowercase_		:      List[Any]          =       functional.normalize(a					,       mean=self.mean					,       std=self.std     )
       return image, target


class     _UpperCAmelCase  :




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






       '''simple docstring'''






       if not isinstance(a					,       np.ndarray     ):
          lowercase_		:      Optional[int]          =       np.array(a     ).astype(np.uinta     )
       # avoid using underflow conversion
       lowercase_		:      Optional[Any]          =       2_5_5
       lowercase_		:      List[Any]          =       target - 1
       lowercase_		:      List[Any]          =       2_5_5

       lowercase_		:      List[str]          =       Image.fromarray(a     )
       return image, target


@dataclass
class     _UpperCAmelCase  :
    __lowerCamelCase:				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).'
        }			,   )
    __lowerCamelCase:				Optional[str]						    =      field(
        default=snake_case			,   metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}     )
    __lowerCamelCase:				Optional[float]						    =      field(
        default=0.15			,   metadata={'help': 'Percent to split off of train for validation.'}     )
    __lowerCamelCase:				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.'
            )
        }			,   )
    __lowerCamelCase:				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.'
            )
        }			,   )
    __lowerCamelCase:				Optional[bool]						    =      field(
        default=snake_case			,   metadata={'help': 'Whether or not to reduce all labels by 1 and replace background by 255.'}			,   )




    def 			lowerCAmelCase__			(     self					:    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     _UpperCAmelCase  :
    __lowerCamelCase:				str						    =      field(
        default='nvidia/mit-b0'			,   metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}			,   )
    __lowerCamelCase:				Optional[str]						    =      field(
        default=snake_case			,   metadata={'help': 'Pretrained config name or path if not the same as model_name'}     )
    __lowerCamelCase:				Optional[str]						    =      field(
        default=snake_case			,   metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'}     )
    __lowerCamelCase:				str						    =      field(
        default='main'			,   metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}			,   )
    __lowerCamelCase:				str						    =      field(default=snake_case			,   metadata={'help': 'Name or path of preprocessor config.'}     )
    __lowerCamelCase:				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"""




   lowercase_		:      Union[str, Any]          =       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_		:      List[Any]          =       parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]							)							)
   else:
      lowercase_      ,						lowercase_      ,						lowercase_		:      int          =       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_		:      Any          =       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_		:      int          =       None
   if os.path.isdir(training_args.output_dir							) and training_args.do_train and not training_args.overwrite_output_dir:
      lowercase_		:      List[str]          =       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_		:      List[str]          =       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_		:      Dict          =       dataset.rename_columns({"pixel_values": "image"}							)
   if "annotation" in dataset["train"].column_names:
      lowercase_		:      int          =       dataset.rename_columns({"annotation": "label"}							)

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

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

      lowercase_		:      Dict          =       logits_tensor.detach().cpu().numpy()
      lowercase_		:      Tuple          =       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_		:      Any          =       metrics.pop("per_category_accuracy"							).tolist()
      lowercase_		:      Any          =       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_		:      Dict          =       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_		:      Any          =       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_		:      List[Any]          =       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_		:      Union[str, Any]          =       (image_processor.size["shortest_edge"], image_processor.size["shortest_edge"])
   else:
      lowercase_		:      Optional[Any]          =       (image_processor.size["height"], image_processor.size["width"])
   lowercase_		:      Optional[int]          =       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_		:      List[str]          =       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							):
      lowercase_		:      Union[str, Any]          =       []
      lowercase_		:      List[str]          =       []
      for image, target in zip(example_batch["image"]  ,						example_batch["label"]							):
         lowercase_      ,						lowercase_		:      Tuple          =       train_transforms(image.convert("RGB"							)  ,						_UpperCamelCase							)
         pixel_values.append(_UpperCamelCase							)
         labels.append(_UpperCamelCase							)

      lowercase_		:      Optional[int]          =       {}
      lowercase_		:      Optional[int]          =       torch.stack(_UpperCamelCase							)
      lowercase_		:      str          =       torch.stack(_UpperCamelCase							)

      return encoding

   def preprocess_val(_UpperCamelCase							):
      lowercase_		:      Dict          =       []
      lowercase_		:      Optional[Any]          =       []
      for image, target in zip(example_batch["image"]  ,						example_batch["label"]							):
         lowercase_      ,						lowercase_		:      Dict          =       val_transforms(image.convert("RGB"							)  ,						_UpperCamelCase							)
         pixel_values.append(_UpperCamelCase							)
         labels.append(_UpperCamelCase							)

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

   # Write model card and (optionally) push to hub
   lowercase_		:      Union[str, Any]          =       {
       "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'''
def 						__SCREAMING_SNAKE_CASE   (					_UpperCamelCase  ,						_UpperCamelCase							):


   """simple docstring"""




   sequence.append(_UpperCamelCase							)

   lowercase_		:      Union[str, Any]          =       0
   while sequence[index] != target:
      index += 1

   sequence.pop()

   if index == len(_UpperCamelCase							):
      return None

   return index


if __name__ == "__main__":
 UpperCamelCase__	=     input('Enter numbers separated by comma:\n').strip()
 UpperCamelCase__	=     [int(item) for item in user_input.split(',')]

 UpperCamelCase__	=     input('Enter a single number to be found in the list:\n')
 UpperCamelCase__	=     int(target_input)
 UpperCamelCase__	=     sentinel_linear_search(sequence, target)
 if result is not None:
  print(f"""{target} found at positions: {result}""")
 else:
  print('Not found')




