






'''simple docstring'''
import unittest

import numpy as np
from datasets import load_dataset

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 BeitImageProcessor


class 							_UpperCAmelCase    (		unittest.TestCase      ):




    def __init__(      self	:							List[Any]	,  a	:							int	,  a	:							Any=7	,  a	:							List[str]=3	,  a	:							Tuple=1_8	,  a	:							List[Any]=3_0	,  a	:							Union[str, Any]=4_0_0	,  a	:							Union[str, Any]=True	,  a	:							int=None	,  a	:							Optional[Any]=True	,  a	:							List[str]=None	,  a	:							int=True	,  a	:							List[Any]=[0.5, 0.5, 0.5]	,  a	:							Optional[Any]=[0.5, 0.5, 0.5]	,  a	:							Tuple=False	,  ):






       '''simple docstring'''






       lowercase_						:     Union[str, Any]							     =  size if size is not None else {"height": 2_0, "width": 2_0}
       lowercase_						:     Union[str, Any]							     =  crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
       lowercase_						:     Tuple							     =  parent
       lowercase_						:     List[str]							     =  batch_size
       lowercase_						:     Any							     =  num_channels
       lowercase_						:     str							     =  image_size
       lowercase_						:     int							     =  min_resolution
       lowercase_						:     int							     =  max_resolution
       lowercase_						:     Union[str, Any]							     =  do_resize
       lowercase_						:     Union[str, Any]							     =  size
       lowercase_						:     Optional[Any]							     =  do_center_crop
       lowercase_						:     Any							     =  crop_size
       lowercase_						:     Union[str, Any]							     =  do_normalize
       lowercase_						:     Dict							     =  image_mean
       lowercase_						:     str							     =  image_std
       lowercase_						:     List[Any]							     =  do_reduce_labels





    def 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''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_reduce_labels": self.do_reduce_labels,
       }




def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   lowercase_						:     str							     =  load_dataset("hf-internal-testing/fixtures_ade20k"    ,		split="test"				)

   lowercase_						:     Union[str, Any]							     =  Image.open(dataset[0]["file"]				)
   lowercase_						:     List[str]							     =  Image.open(dataset[1]["file"]				)

   return image, map




def 		__SCREAMING_SNAKE_CASE       (	):


   """simple docstring"""




   lowercase_						:     Union[str, Any]							     =  load_dataset("hf-internal-testing/fixtures_ade20k"    ,		split="test"				)

   lowercase_						:     Optional[int]							     =  Image.open(ds[0]["file"]				)
   lowercase_						:     Union[str, Any]							     =  Image.open(ds[1]["file"]				)
   lowercase_						:     Tuple							     =  Image.open(ds[2]["file"]				)
   lowercase_						:     List[str]							     =  Image.open(ds[3]["file"]				)

   return [imagea, imagea], [mapa, mapa]





@require_torch
@require_vision
class 							_UpperCAmelCase    (		snake_case					,       unittest.TestCase      ):
    __lowerCamelCase: Optional[int]									=     BeitImageProcessor if is_vision_available() else None




    def 					lowerCAmelCase__					(      self	:							Union[str, Any]      ):






       '''simple docstring'''






       lowercase_						:     List[str]							     =  BeitImageProcessingTester(self      )




    @property
    def 					lowerCAmelCase__					(      self	:							Union[str, Any]      ):






       '''simple docstring'''






       return self.image_processor_tester.prepare_image_processor_dict()




    def 					lowerCAmelCase__					(      self	:							List[str]      ):






       '''simple docstring'''






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




    def 					lowerCAmelCase__					(      self	:							List[Any]      ):






       '''simple docstring'''






       lowercase_						:     Optional[Any]							     =  self.image_processing_class.from_dict(self.image_processor_dict      )
       self.assertEqual(image_processor.size	,  {"height": 2_0, "width": 2_0}      )
       self.assertEqual(image_processor.crop_size	,  {"height": 1_8, "width": 1_8}      )
       self.assertEqual(image_processor.do_reduce_labels	,  a      )

       lowercase_						:     Optional[Any]							     =  self.image_processing_class.from_dict(
           self.image_processor_dict	,  size=4_2	,  crop_size=8_4	,  reduce_labels=a      )
       self.assertEqual(image_processor.size	,  {"height": 4_2, "width": 4_2}      )
       self.assertEqual(image_processor.crop_size	,  {"height": 8_4, "width": 8_4}      )
       self.assertEqual(image_processor.do_reduce_labels	,  a      )




    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       pass




    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






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

       # Test not batched input
       lowercase_						:     Dict							     =  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_						:     str							     =  image_processing(a	,  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 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     int							     =  self.image_processing_class(**self.image_processor_dict      )
       # create random numpy tensors
       lowercase_						:     Union[str, Any]							     =  prepare_image_inputs(self.image_processor_tester	,  equal_resolution=a	,  numpify=a      )
       for image in image_inputs:
          self.assertIsInstance(a	,  np.ndarray      )

       # Test not batched input
       lowercase_						:     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
       lowercase_						:     Union[str, Any]							     =  image_processing(a	,  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 					lowerCAmelCase__					(      self	:							Optional[Any]      ):






       '''simple docstring'''






       lowercase_						:     Any							     =  self.image_processing_class(**self.image_processor_dict      )
       # create random PyTorch tensors
       lowercase_						:     Tuple							     =  prepare_image_inputs(self.image_processor_tester	,  equal_resolution=a	,  torchify=a      )
       for image in image_inputs:
          self.assertIsInstance(a	,  torch.Tensor      )

       # Test not batched input
       lowercase_						:     List[str]							     =  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_						:     Tuple							     =  image_processing(a	,  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 					lowerCAmelCase__					(      self	:							Tuple      ):






       '''simple docstring'''






       lowercase_						:     Tuple							     =  self.image_processing_class(**self.image_processor_dict      )
       # create random PyTorch tensors
       lowercase_						:     str							     =  prepare_image_inputs(self.image_processor_tester	,  equal_resolution=a	,  torchify=a      )
       lowercase_						:     Tuple							     =  []
       for image in image_inputs:
          self.assertIsInstance(a	,  torch.Tensor      )
          maps.append(torch.zeros(image.shape[-2:]      ).long()      )

       # Test not batched input
       lowercase_						:     Union[str, Any]							     =  image_processing(image_inputs[0]	,  maps[0]	,  return_tensors="pt"      )
       self.assertEqual(
           encoding["pixel_values"].shape	,  (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(
           encoding["labels"].shape	,  (
               1,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(encoding["labels"].dtype	,  torch.long      )
       self.assertTrue(encoding["labels"].min().item() >= 0      )
       self.assertTrue(encoding["labels"].max().item() <= 2_5_5      )

       # Test batched
       lowercase_						:     str							     =  image_processing(a	,  a	,  return_tensors="pt"      )
       self.assertEqual(
           encoding["pixel_values"].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"],
           )	,  )
       self.assertEqual(
           encoding["labels"].shape	,  (
               self.image_processor_tester.batch_size,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(encoding["labels"].dtype	,  torch.long      )
       self.assertTrue(encoding["labels"].min().item() >= 0      )
       self.assertTrue(encoding["labels"].max().item() <= 2_5_5      )

       # Test not batched input (PIL images)
       lowercase_     ,		lowercase_						:     Dict							     =  prepare_semantic_single_inputs()

       lowercase_						:     Tuple							     =  image_processing(a	,  a	,  return_tensors="pt"      )
       self.assertEqual(
           encoding["pixel_values"].shape	,  (
               1,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(
           encoding["labels"].shape	,  (
               1,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(encoding["labels"].dtype	,  torch.long      )
       self.assertTrue(encoding["labels"].min().item() >= 0      )
       self.assertTrue(encoding["labels"].max().item() <= 2_5_5      )

       # Test batched input (PIL images)
       lowercase_     ,		lowercase_						:     int							     =  prepare_semantic_batch_inputs()

       lowercase_						:     Tuple							     =  image_processing(a	,  a	,  return_tensors="pt"      )
       self.assertEqual(
           encoding["pixel_values"].shape	,  (
               2,
               self.image_processor_tester.num_channels,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(
           encoding["labels"].shape	,  (
               2,
               self.image_processor_tester.crop_size["height"],
               self.image_processor_tester.crop_size["width"],
           )	,  )
       self.assertEqual(encoding["labels"].dtype	,  torch.long      )
       self.assertTrue(encoding["labels"].min().item() >= 0      )
       self.assertTrue(encoding["labels"].max().item() <= 2_5_5      )





    def 					lowerCAmelCase__					(      self	:							List[str]      ):






       '''simple docstring'''






       lowercase_						:     int							     =  self.image_processing_class(**self.image_processor_dict      )

       # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
       lowercase_     ,		lowercase_						:     str							     =  prepare_semantic_single_inputs()
       lowercase_						:     int							     =  image_processing(a	,  a	,  return_tensors="pt"      )
       self.assertTrue(encoding["labels"].min().item() >= 0      )
       self.assertTrue(encoding["labels"].max().item() <= 1_5_0      )

       lowercase_						:     int							     =  True
       lowercase_						:     List[str]							     =  image_processing(a	,  a	,  return_tensors="pt"      )
       self.assertTrue(encoding["labels"].min().item() >= 0      )
       self.assertTrue(encoding["labels"].max().item() <= 2_5_5      )












'''simple docstring'''
import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


UpperCamelCase__			=      False
try:
 UpperCamelCase__			=      _is_package_available('google.colab')
except ModuleNotFoundError:
 pass


@input.register
class 							_UpperCAmelCase    :




    def __init__(      self	:							List[Any]	,  a	:							str = None	,  a	:							list = []      ):






       '''simple docstring'''






       lowercase_						:     Optional[Any]							     =  0
       lowercase_						:     Dict							     =  choices
       lowercase_						:     List[str]							     =  prompt
       if sys.platform == "win32":
          lowercase_						:     List[Any]							     =  "*"
       else:
          lowercase_						:     Union[str, Any]							     =  "➔ "




    def 					lowerCAmelCase__					(      self	:							int	,  a	:							Optional[int]	,  a	:							str = ""      ):






       '''simple docstring'''






       if sys.platform != "win32":
          writeColor(self.choices[index]	,  3_2	,  a      )
       else:
          forceWrite(self.choices[index]	,  a      )




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






       '''simple docstring'''






       if index == self.position:
          forceWrite(f""" {self.arrow_char} """      )
          self.write_choice(a      )
       else:
          forceWrite(f"""    {self.choices[index]}"""      )
       reset_cursor()




    def 					lowerCAmelCase__					(      self	:							str	,  a	:							Direction	,  a	:							int = 1      ):






       '''simple docstring'''






       lowercase_						:     Optional[int]							     =  self.position
       if direction == Direction.DOWN:
          if self.position + 1 >= len(self.choices      ):
             return
          self.position += num_spaces
       else:
          if self.position - 1 < 0:
             return
          self.position -= num_spaces
       clear_line()
       self.print_choice(a      )
       move_cursor(a	,  direction.name      )
       self.print_choice(self.position      )




    @input.mark(KEYMAP["up"]      )
    def 					lowerCAmelCase__					(      self	:							Dict      ):






       '''simple docstring'''






       self.move_direction(Direction.UP      )




    @input.mark(KEYMAP["down"]      )
    def 					lowerCAmelCase__					(      self	:							List[Any]      ):






       '''simple docstring'''






       self.move_direction(Direction.DOWN      )




    @input.mark(KEYMAP["newline"]      )
    def 					lowerCAmelCase__					(      self	:							Any      ):






       '''simple docstring'''






       move_cursor(len(self.choices      ) - self.position	,  "DOWN"      )
       return self.position




    @input.mark(KEYMAP["interrupt"]      )
    def 					lowerCAmelCase__					(      self	:							str      ):






       '''simple docstring'''






       move_cursor(len(self.choices      ) - self.position	,  "DOWN"      )
       raise KeyboardInterrupt




    @input.mark_multiple(*[KEYMAP[str(a      )] for number in range(1_0      )]      )
    def 					lowerCAmelCase__					(      self	:							int      ):






       '''simple docstring'''






       lowercase_						:     str							     =  int(chr(self.current_selection      )      )
       lowercase_						:     Tuple							     =  index - self.position
       if index == self.position:
          return
       if index < len(self.choices      ):
          if self.position > index:
             self.move_direction(Direction.UP	,  -movement      )
          elif self.position < index:
             self.move_direction(Direction.DOWN	,  a      )
          else:
             return
       else:
          return





    def 					lowerCAmelCase__					(      self	:							Tuple	,  a	:							int = 0      ):






       '''simple docstring'''






       if self.prompt:
          linebreak()
          forceWrite(self.prompt	,  "\n"      )
          if in_colab:
             forceWrite("Please input a choice index (starting from 0), and press enter"	,  "\n"      )
          else:
             forceWrite("Please select a choice using the arrow or number keys, and selecting with enter"	,  "\n"      )
       lowercase_						:     Dict							     =  default_choice
       for i in range(len(self.choices      )      ):
          self.print_choice(a      )
          forceWrite("\n"      )
       move_cursor(len(self.choices      ) - self.position	,  "UP"      )
       with cursor.hide():
          while True:
             if in_colab:
                try:
                   lowercase_						:     List[str]							     =  int(builtins.input()      )
                except ValueError:
                   lowercase_						:     List[Any]							     =  default_choice
             else:
                lowercase_						:     Dict							     =  self.handle_input()
             if choice is not None:
                reset_cursor()
                for _ in range(len(self.choices      ) + 1      ):
                   move_cursor(1	,  "UP"      )
                   clear_line()
                self.write_choice(a	,  "\n"      )
                return choice




