'''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 SegformerImageProcessor




class 					a__   (     unittest.TestCase				):






     def __init__(				self	:	List[str]						,       a	:	Union[str, Any]						,       a	:	Union[str, Any]=7						,       a	:	Dict=3						,       a	:	str=30						,       a	:	Optional[Any]=4_00						,       a	:	Union[str, Any]=True						,       a	:	Any=None						,       a	:	List[Any]=True						,       a	:	Union[str, Any]=[0.5, 0.5, 0.5]						,       a	:	str=[0.5, 0.5, 0.5]						,       a	:	List[Any]=False						,       ):





         """simple docstring"""



         __lowerCamelCase						=						size if size is not None else {'''height''': 30, '''width''': 30}
         __lowerCamelCase						=						parent
         __lowerCamelCase						=						batch_size
         __lowerCamelCase						=						num_channels
         __lowerCamelCase						=						min_resolution
         __lowerCamelCase						=						max_resolution
         __lowerCamelCase						=						do_resize
         __lowerCamelCase						=						size
         __lowerCamelCase						=						do_normalize
         __lowerCamelCase						=						image_mean
         __lowerCamelCase						=						image_std
         __lowerCamelCase						=						do_reduce_labels






     def      SCREAMING_SNAKE_CASE__     (				self	:	str					):





         """simple docstring"""



         return {
             "do_resize": self.do_resize,
             "size": self.size,
             "do_normalize": self.do_normalize,
             "image_mean": self.image_mean,
             "image_std": self.image_std,
             "do_reduce_labels": self.do_reduce_labels,
         }






def __lowerCAmelCase				(							)			->					Optional[int]:
    __lowerCamelCase						=						load_dataset('''hf-internal-testing/fixtures_ade20k'''       ,						split='''test'''       )

    __lowerCamelCase						=						Image.open(dataset[0]['''file''']       )
    __lowerCamelCase						=						Image.open(dataset[1]['''file''']       )

    return image, map






def __lowerCAmelCase				(							)			->					List[str]:
    __lowerCamelCase						=						load_dataset('''hf-internal-testing/fixtures_ade20k'''       ,						split='''test'''       )

    __lowerCamelCase						=						Image.open(dataset[0]['''file''']       )
    __lowerCamelCase						=						Image.open(dataset[1]['''file''']       )
    __lowerCamelCase						=						Image.open(dataset[2]['''file''']       )
    __lowerCamelCase						=						Image.open(dataset[3]['''file''']       )

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




@require_torch
@require_vision
class 					a__   (     UpperCAmelCase__							,     unittest.TestCase				):
     lowerCamelCase						:  Optional[int]							=SegformerImageProcessor if is_vision_available() else None






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict					):





         """simple docstring"""



         __lowerCamelCase						=						SegformerImageProcessingTester(self					)






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





         """simple docstring"""



         return self.image_processor_tester.prepare_image_processor_dict()






     def      SCREAMING_SNAKE_CASE__     (				self	:	int					):





         """simple docstring"""



         __lowerCamelCase						=						self.image_processing_class(**self.image_processor_dict					)
         self.assertTrue(hasattr(a						,       '''do_resize'''					)					)
         self.assertTrue(hasattr(a						,       '''size'''					)					)
         self.assertTrue(hasattr(a						,       '''do_normalize'''					)					)
         self.assertTrue(hasattr(a						,       '''image_mean'''					)					)
         self.assertTrue(hasattr(a						,       '''image_std'''					)					)
         self.assertTrue(hasattr(a						,       '''do_reduce_labels'''					)					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[str]					):





         """simple docstring"""



         __lowerCamelCase						=						self.image_processing_class.from_dict(self.image_processor_dict					)
         self.assertEqual(image_processor.size						,       {'''height''': 30, '''width''': 30}					)
         self.assertEqual(image_processor.do_reduce_labels						,       a					)

         __lowerCamelCase						=						self.image_processing_class.from_dict(self.image_processor_dict						,       size=42						,       reduce_labels=a					)
         self.assertEqual(image_processor.size						,       {'''height''': 42, '''width''': 42}					)
         self.assertEqual(image_processor.do_reduce_labels						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	str					):





         """simple docstring"""



         pass






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any					):





         """simple docstring"""



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

         # Test not batched input
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )

         # Test batched
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict					):





         """simple docstring"""



         __lowerCamelCase						=						self.image_processing_class(**self.image_processor_dict					)
         # create random numpy tensors
         __lowerCamelCase						=						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
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )

         # Test batched
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )






     def      SCREAMING_SNAKE_CASE__     (				self	:	Dict					):





         """simple docstring"""



         __lowerCamelCase						=						self.image_processing_class(**self.image_processor_dict					)
         # create random PyTorch tensors
         __lowerCamelCase						=						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
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )

         # Test batched
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )






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





         """simple docstring"""



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

         # Test not batched input
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(
             encoding['''labels'''].shape						,       (
                 1,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(encoding['''labels'''].dtype						,       torch.long					)
         self.assertTrue(encoding['''labels'''].min().item() >= 0					)
         self.assertTrue(encoding['''labels'''].max().item() <= 2_55					)

         # Test batched
         __lowerCamelCase						=						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.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(
             encoding['''labels'''].shape						,       (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(encoding['''labels'''].dtype						,       torch.long					)
         self.assertTrue(encoding['''labels'''].min().item() >= 0					)
         self.assertTrue(encoding['''labels'''].max().item() <= 2_55					)

         # Test not batched input (PIL images)
         __lowerCamelCase			,						__lowerCamelCase						=						prepare_semantic_single_inputs()

         __lowerCamelCase						=						image_processing(a						,       a						,       return_tensors='''pt'''					)
         self.assertEqual(
             encoding['''pixel_values'''].shape						,       (
                 1,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(
             encoding['''labels'''].shape						,       (
                 1,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(encoding['''labels'''].dtype						,       torch.long					)
         self.assertTrue(encoding['''labels'''].min().item() >= 0					)
         self.assertTrue(encoding['''labels'''].max().item() <= 2_55					)

         # Test batched input (PIL images)
         __lowerCamelCase			,						__lowerCamelCase						=						prepare_semantic_batch_inputs()

         __lowerCamelCase						=						image_processing(a						,       a						,       return_tensors='''pt'''					)
         self.assertEqual(
             encoding['''pixel_values'''].shape						,       (
                 2,
                 self.image_processor_tester.num_channels,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(
             encoding['''labels'''].shape						,       (
                 2,
                 self.image_processor_tester.size['''height'''],
                 self.image_processor_tester.size['''width'''],
             )						,       )
         self.assertEqual(encoding['''labels'''].dtype						,       torch.long					)
         self.assertTrue(encoding['''labels'''].min().item() >= 0					)
         self.assertTrue(encoding['''labels'''].max().item() <= 2_55					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	int					):





         """simple docstring"""



         __lowerCamelCase						=						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
         __lowerCamelCase			,						__lowerCamelCase						=						prepare_semantic_single_inputs()
         __lowerCamelCase						=						image_processing(a						,       a						,       return_tensors='''pt'''					)
         self.assertTrue(encoding['''labels'''].min().item() >= 0					)
         self.assertTrue(encoding['''labels'''].max().item() <= 1_50					)

         __lowerCamelCase						=						True
         __lowerCamelCase						=						image_processing(a						,       a						,       return_tensors='''pt'''					)
         self.assertTrue(encoding['''labels'''].min().item() >= 0					)
         self.assertTrue(encoding['''labels'''].max().item() <= 2_55					)

'''simple docstring'''




from __future__ import annotations






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					list:
    __lowerCamelCase						=						[None] * (len(UpperCamelCase__       ) + len(UpperCamelCase__       ))

    __lowerCamelCase						=						0  # pointer to current index for left Half
    __lowerCamelCase						=						0  # pointer to current index for the right Half
    __lowerCamelCase						=						0  # pointer to current index for the sorted array Half

    while pointera < len(UpperCamelCase__       ) and pointera < len(UpperCamelCase__       ):
        if left_half[pointera] < right_half[pointera]:
            __lowerCamelCase						=						left_half[pointera]
            pointera += 1
            index += 1
        else:
            __lowerCamelCase						=						right_half[pointera]
            pointera += 1
            index += 1
    while pointera < len(UpperCamelCase__       ):
        __lowerCamelCase						=						left_half[pointera]
        pointera += 1
        index += 1

    while pointera < len(UpperCamelCase__       ):
        __lowerCamelCase						=						right_half[pointera]
        pointera += 1
        index += 1

    return sorted_array






def __lowerCAmelCase				(							UpperCamelCase__       )			->					list:
    if len(UpperCamelCase__       ) <= 1:
        return array
    # the actual formula to calculate the middle element = left + (right - left) // 2
    # this avoids integer overflow in case of large N
    __lowerCamelCase						=						0 + (len(UpperCamelCase__       ) - 0) // 2

    # Split the array into halves till the array length becomes equal to One
    # merge the arrays of single length returned by mergeSort function and
    # pass them into the merge arrays function which merges the array
    __lowerCamelCase						=						array[:middle]
    __lowerCamelCase						=						array[middle:]

    return merge(merge_sort(UpperCamelCase__       )       ,						merge_sort(UpperCamelCase__       )       )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
