






"""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				,						_lowerCamelCase				,						_lowerCamelCase=7				,						_lowerCamelCase=3				,						_lowerCamelCase=3_0				,						_lowerCamelCase=4_0_0				,						_lowerCamelCase=True				,						_lowerCamelCase=None				,						_lowerCamelCase=True				,						_lowerCamelCase=[0.5, 0.5, 0.5]				,						_lowerCamelCase=[0.5, 0.5, 0.5]				,						_lowerCamelCase=False				,						):
      lowercase				       =			size if size is not None else {'height': 3_0, 'width': 3_0}
      lowercase				       =			parent
      lowercase				       =			batch_size
      lowercase				       =			num_channels
      lowercase				       =			min_resolution
      lowercase				       =			max_resolution
      lowercase				       =			do_resize
      lowercase				       =			size
      lowercase				       =			do_normalize
      lowercase				       =			image_mean
      lowercase				       =			image_std
      lowercase				       =			do_reduce_labels







    def      UpperCamelCase_ (     self			):
      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 		_SCREAMING_SNAKE_CASE					(       ):





  '''simple docstring'''





  lowercase				       =			load_dataset('hf-internal-testing/fixtures_ade20k'						,   split='test'       )

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

  return image, map
def 		_SCREAMING_SNAKE_CASE					(       ):





  '''simple docstring'''





  lowercase				       =			load_dataset('hf-internal-testing/fixtures_ade20k'						,   split='test'       )

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

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



@require_torch
@require_vision
class 			a	(  a_,							unittest.TestCase      ):
    UpperCAmelCase_					:	List[str]      	=SegformerImageProcessor if is_vision_available() else None







    def      UpperCamelCase_ (     self			):
      lowercase				       =			SegformerImageProcessingTester(self			)







    @property
    def      UpperCamelCase_ (     self			):
      return self.image_processor_tester.prepare_image_processor_dict()







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.image_processing_class(**self.image_processor_dict			)
      self.assertTrue(hasattr(_lowerCamelCase				,						'do_resize'			)			)
      self.assertTrue(hasattr(_lowerCamelCase				,						'size'			)			)
      self.assertTrue(hasattr(_lowerCamelCase				,						'do_normalize'			)			)
      self.assertTrue(hasattr(_lowerCamelCase				,						'image_mean'			)			)
      self.assertTrue(hasattr(_lowerCamelCase				,						'image_std'			)			)
      self.assertTrue(hasattr(_lowerCamelCase				,						'do_reduce_labels'			)			)







    def      UpperCamelCase_ (     self			):
      lowercase				       =			self.image_processing_class.from_dict(self.image_processor_dict			)
      self.assertEqual(image_processor.size				,						{'height': 3_0, 'width': 3_0}			)
      self.assertEqual(image_processor.do_reduce_labels				,						_lowerCamelCase			)

      lowercase				       =			self.image_processing_class.from_dict(self.image_processor_dict				,						size=4_2				,						reduce_labels=_lowerCamelCase			)
      self.assertEqual(image_processor.size				,						{'height': 4_2, 'width': 4_2}			)
      self.assertEqual(image_processor.do_reduce_labels				,						_lowerCamelCase			)







    def      UpperCamelCase_ (     self			):
      pass







    def      UpperCamelCase_ (     self			):
      # Initialize image_processing
      lowercase				       =			self.image_processing_class(**self.image_processor_dict			)
      # create random PIL images
      lowercase				       =			prepare_image_inputs(self.image_processor_tester				,						equal_resolution=_lowerCamelCase			)
      for image in image_inputs:
        self.assertIsInstance(_lowerCamelCase				,						Image.Image			)

      # Test not batched input
      lowercase				       =			image_processing(image_inputs[0]				,						return_tensors='pt'			).pixel_values
      self.assertEqual(
          encoded_images.shape				,						(
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size['height'],
              self.image_processor_tester.size['width'],
          )				,						)

      # Test batched
      lowercase				       =			image_processing(_lowerCamelCase				,						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      UpperCamelCase_ (     self			):
      # Initialize image_processing
      lowercase				       =			self.image_processing_class(**self.image_processor_dict			)
      # create random numpy tensors
      lowercase				       =			prepare_image_inputs(self.image_processor_tester				,						equal_resolution=_lowerCamelCase				,						numpify=_lowerCamelCase			)
      for image in image_inputs:
        self.assertIsInstance(_lowerCamelCase				,						np.ndarray			)

      # Test not batched input
      lowercase				       =			image_processing(image_inputs[0]				,						return_tensors='pt'			).pixel_values
      self.assertEqual(
          encoded_images.shape				,						(
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size['height'],
              self.image_processor_tester.size['width'],
          )				,						)

      # Test batched
      lowercase				       =			image_processing(_lowerCamelCase				,						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      UpperCamelCase_ (     self			):
      # Initialize image_processing
      lowercase				       =			self.image_processing_class(**self.image_processor_dict			)
      # create random PyTorch tensors
      lowercase				       =			prepare_image_inputs(self.image_processor_tester				,						equal_resolution=_lowerCamelCase				,						torchify=_lowerCamelCase			)
      for image in image_inputs:
        self.assertIsInstance(_lowerCamelCase				,						torch.Tensor			)

      # Test not batched input
      lowercase				       =			image_processing(image_inputs[0]				,						return_tensors='pt'			).pixel_values
      self.assertEqual(
          encoded_images.shape				,						(
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.size['height'],
              self.image_processor_tester.size['width'],
          )				,						)

      # Test batched
      lowercase				       =			image_processing(_lowerCamelCase				,						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      UpperCamelCase_ (     self			):
      # Initialize image_processing
      lowercase				       =			self.image_processing_class(**self.image_processor_dict			)
      # create random PyTorch tensors
      lowercase				       =			prepare_image_inputs(self.image_processor_tester				,						equal_resolution=_lowerCamelCase				,						torchify=_lowerCamelCase			)
      lowercase				       =			[]
      for image in image_inputs:
        self.assertIsInstance(_lowerCamelCase				,						torch.Tensor			)
        maps.append(torch.zeros(image.shape[-2:]			).long()			)

      # Test not batched input
      lowercase				       =			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_5_5			)

      # Test batched
      lowercase				       =			image_processing(_lowerCamelCase				,						_lowerCamelCase				,						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_5_5			)

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

      lowercase				       =			image_processing(_lowerCamelCase				,						_lowerCamelCase				,						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_5_5			)

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

      lowercase				       =			image_processing(_lowerCamelCase				,						_lowerCamelCase				,						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_5_5			)







    def      UpperCamelCase_ (     self			):
      # Initialize image_processing
      lowercase				       =			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				       =			prepare_semantic_single_inputs()
      lowercase				       =			image_processing(_lowerCamelCase				,						_lowerCamelCase				,						return_tensors='pt'			)
      self.assertTrue(encoding['labels'].min().item() >= 0			)
      self.assertTrue(encoding['labels'].max().item() <= 1_5_0			)

      lowercase				       =			True
      lowercase				       =			image_processing(_lowerCamelCase				,						_lowerCamelCase				,						return_tensors='pt'			)
      self.assertTrue(encoding['labels'].min().item() >= 0			)
      self.assertTrue(encoding['labels'].max().item() <= 2_5_5			)




import functools
from math import sqrt
from time import time

def    UpperCamelCase_ (	a_  ,				*a_  ,				**a_		)     ->List[Any]:
		A				=time()
		A				=func(*a_  ,				**a_		)
		A				=time()
		if int(end - start		) > 0:
				print(f'''{func.__name__} runtime: {(end - start):0.4f} s'''		)
		else:
				print(f'''{func.__name__} runtime: {(end - start) * 1000:0.4f} ms'''		)
		return output

def    UpperCamelCase_ (	a_		)     ->list[int]:
		if n < 0:
				raise Exception("n is negative"		)
		if n == 0:
				return [0]
		A				=[0, 1]
		for _ in range(n - 1		):
				fib.append(fib[-1] + fib[-2]		)
		return fib

def    UpperCamelCase_ (	a_		)     ->list[int]:

		def fib_recursive_term(a_		) -> int:
				if i < 0:
						raise Exception("n is negative"		)
				if i < 2:
						return i
				return fib_recursive_term(i - 1		) + fib_recursive_term(i - 2		)

		if n < 0:
				raise Exception("n is negative"		)
		return [fib_recursive_term(a_		) for i in range(n + 1		)]

def    UpperCamelCase_ (	a_		)     ->list[int]:

		@functools.cache
		def fib_recursive_term(a_		) -> int:
				if i < 0:
						raise Exception("n is negative"		)
				if i < 2:
						return i
				return fib_recursive_term(i - 1		) + fib_recursive_term(i - 2		)

		if n < 0:
				raise Exception("n is negative"		)
		return [fib_recursive_term(a_		) for i in range(n + 1		)]

def    UpperCamelCase_ (	a_		)     ->list[int]:
		if n < 0:
				raise Exception("n is negative"		)
		# Cache must be outside recursuive function
		# other it will reset every time it calls itself.
		A				={0: 0, 1: 1, 2: 1}  # Prefilled cache

		def rec_fn_memoized(a_		) -> int:
				if num in cache:
						return cache[num]

				A				=rec_fn_memoized(num - 1		) + rec_fn_memoized(num - 2		)
				A				=value
				return value

		return [rec_fn_memoized(a_		) for i in range(n + 1		)]

def    UpperCamelCase_ (	a_		)     ->list[int]:
		if n < 0:
				raise Exception("n is negative"		)
		if n >= 1475:
				raise Exception("n is too large"		)
		A				=sqrt(5		)
		A				=(1 + sqrt_a) / 2
		return [round(phi**i / sqrt_a		) for i in range(n + 1		)]


if __name__ == "__main__":
	__a							  =						3_0
	time_func(fib_iterative, num)
	time_func(fib_recursive, num)  # Around 3s runtime
	time_func(fib_recursive_cached, num)  # Around 0ms runtime
	time_func(fib_memoization, num)
	time_func(fib_binet, num)




