

'''simple docstring'''







import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
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 DetaImageProcessor


class        A__   (   unittest.TestCase      ):



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__=7		,					UpperCamelCase__=3		,					UpperCamelCase__=30		,					UpperCamelCase__=400		,					UpperCamelCase__=True		,					UpperCamelCase__=None		,					UpperCamelCase__=True		,					UpperCamelCase__=[0.5, 0.5, 0.5]		,					UpperCamelCase__=[0.5, 0.5, 0.5]		,					UpperCamelCase__=True		,					UpperCamelCase__=1 / 255		,					UpperCamelCase__=True		,					)    ->   Optional[int]:





           '''simple docstring'''
           # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
           A_						       =   size if size is not None else {"""shortest_edge""": 18, """longest_edge""": 1333}
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   num_channels
           A_						       =   min_resolution
           A_						       =   max_resolution
           A_						       =   do_resize
           A_						       =   size
           A_						       =   do_normalize
           A_						       =   image_mean
           A_						       =   image_std
           A_						       =   do_rescale
           A_						       =   rescale_factor
           A_						       =   do_pad



    def        snake_case_      (       self							)    ->   List[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_rescale": self.do_rescale,
               "rescale_factor": self.rescale_factor,
               "do_pad": self.do_pad,
           }







    def        snake_case_      (       self		,					UpperCamelCase__		,					UpperCamelCase__=False							)    ->   Dict:





           '''simple docstring'''
           if not batched:
                  A_						       =   image_inputs[0]
                  if isinstance(UpperCamelCase__		,					Image.Image							):
                         A_       ,      A_						       =   image.size
                  else:
                         A_       ,      A_						       =   image.shape[1], image.shape[2]
                  if w < h:
                         A_						       =   int(self.size["""shortest_edge"""] * h / w							)
                         A_						       =   self.size["""shortest_edge"""]
                  elif w > h:
                         A_						       =   self.size["""shortest_edge"""]
                         A_						       =   int(self.size["""shortest_edge"""] * w / h							)
                  else:
                         A_						       =   self.size["""shortest_edge"""]
                         A_						       =   self.size["""shortest_edge"""]

           else:
                  A_						       =   []
                  for image in image_inputs:
                         A_       ,      A_						       =   self.get_expected_values([image]							)
                         expected_values.append((expected_height, expected_width)							)
                  A_						       =   max(UpperCamelCase__		,					key=lambda UpperCamelCase__							: item[0]							)[0]
                  A_						       =   max(UpperCamelCase__		,					key=lambda UpperCamelCase__							: item[1]							)[1]

           return expected_height, expected_width


@require_torch
@require_vision
class        A__   (   _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		DetaImageProcessor if is_vision_available() else None



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   DetaImageProcessingTester(self							)



    @property
    def        snake_case_      (       self							)    ->   List[str]:





           '''simple docstring'''
           return self.image_processor_tester.prepare_image_processor_dict()



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   self.image_processing_class(**self.image_processor_dict							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""image_mean"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""image_std"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""do_normalize"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""do_resize"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""do_rescale"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""do_pad"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""size"""							)							)



    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   self.image_processing_class.from_dict(self.image_processor_dict							)
           self.assertEqual(image_processor.size		,					{"""shortest_edge""": 18, """longest_edge""": 1333}							)
           self.assertEqual(image_processor.do_pad		,					UpperCamelCase__							)



    def        snake_case_      (       self							)    ->   Tuple:





           '''simple docstring'''
           pass



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           # Initialize image_processing
           A_						       =   self.image_processing_class(**self.image_processor_dict							)
           # create random PIL images
           A_						       =   prepare_image_inputs(self.image_processor_tester		,					equal_resolution=UpperCamelCase__							)
           for image in image_inputs:
                  self.assertIsInstance(UpperCamelCase__		,					Image.Image							)

           # Test not batched input
           A_						       =   image_processing(image_inputs[0]		,					return_tensors="""pt"""							).pixel_values

           A_       ,      A_						       =   self.image_processor_tester.get_expected_values(UpperCamelCase__							)

           self.assertEqual(
               encoded_images.shape		,					(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,					)

           # Test batched
           A_       ,      A_						       =   self.image_processor_tester.get_expected_values(UpperCamelCase__		,					batched=UpperCamelCase__							)

           A_						       =   image_processing(UpperCamelCase__		,					return_tensors="""pt"""							).pixel_values
           self.assertEqual(
               encoded_images.shape		,					(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )		,					)



    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           # Initialize image_processing
           A_						       =   self.image_processing_class(**self.image_processor_dict							)
           # create random numpy tensors
           A_						       =   prepare_image_inputs(self.image_processor_tester		,					equal_resolution=UpperCamelCase__		,					numpify=UpperCamelCase__							)
           for image in image_inputs:
                  self.assertIsInstance(UpperCamelCase__		,					np.ndarray							)

           # Test not batched input
           A_						       =   image_processing(image_inputs[0]		,					return_tensors="""pt"""							).pixel_values

           A_       ,      A_						       =   self.image_processor_tester.get_expected_values(UpperCamelCase__							)

           self.assertEqual(
               encoded_images.shape		,					(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,					)

           # Test batched
           A_						       =   image_processing(UpperCamelCase__		,					return_tensors="""pt"""							).pixel_values

           A_       ,      A_						       =   self.image_processor_tester.get_expected_values(UpperCamelCase__		,					batched=UpperCamelCase__							)

           self.assertEqual(
               encoded_images.shape		,					(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )		,					)



    def        snake_case_      (       self							)    ->   Union[str, Any]:





           '''simple docstring'''
           # Initialize image_processing
           A_						       =   self.image_processing_class(**self.image_processor_dict							)
           # create random PyTorch tensors
           A_						       =   prepare_image_inputs(self.image_processor_tester		,					equal_resolution=UpperCamelCase__		,					torchify=UpperCamelCase__							)
           for image in image_inputs:
                  self.assertIsInstance(UpperCamelCase__		,					torch.Tensor							)

           # Test not batched input
           A_						       =   image_processing(image_inputs[0]		,					return_tensors="""pt"""							).pixel_values

           A_       ,      A_						       =   self.image_processor_tester.get_expected_values(UpperCamelCase__							)

           self.assertEqual(
               encoded_images.shape		,					(1, self.image_processor_tester.num_channels, expected_height, expected_width)		,					)

           # Test batched
           A_						       =   image_processing(UpperCamelCase__		,					return_tensors="""pt"""							).pixel_values

           A_       ,      A_						       =   self.image_processor_tester.get_expected_values(UpperCamelCase__		,					batched=UpperCamelCase__							)

           self.assertEqual(
               encoded_images.shape		,					(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )		,					)



    @slow
    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           # prepare image and target
           A_						       =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
           with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt"""		,					"""r"""							) as f:
                  A_						       =   json.loads(f.read()							)

           A_						       =   {"""image_id""": 39769, """annotations""": target}

           # encode them
           A_						       =   DetaImageProcessor()
           A_						       =   image_processing(images=UpperCamelCase__		,					annotations=UpperCamelCase__		,					return_tensors="""pt"""							)

           # verify pixel values
           A_						       =   torch.Size([1, 3, 800, 1066]							)
           self.assertEqual(encoding["""pixel_values"""].shape		,					UpperCamelCase__							)

           A_						       =   torch.tensor([0.2796, 0.3138, 0.3481]							)
           self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3]		,					UpperCamelCase__		,					atol=1e-4							)							)

           # verify area
           A_						       =   torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""]		,					UpperCamelCase__							)							)
           # verify boxes
           A_						       =   torch.Size([6, 4]							)
           self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape		,					UpperCamelCase__							)
           A_						       =   torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0]		,					UpperCamelCase__		,					atol=1e-3							)							)
           # verify image_id
           A_						       =   torch.tensor([39769]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""]		,					UpperCamelCase__							)							)
           # verify is_crowd
           A_						       =   torch.tensor([0, 0, 0, 0, 0, 0]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""]		,					UpperCamelCase__							)							)
           # verify class_labels
           A_						       =   torch.tensor([75, 75, 63, 65, 17, 17]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""]		,					UpperCamelCase__							)							)
           # verify orig_size
           A_						       =   torch.tensor([480, 640]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""]		,					UpperCamelCase__							)							)
           # verify size
           A_						       =   torch.tensor([800, 1066]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""]		,					UpperCamelCase__							)							)







    @slow
    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           # prepare image, target and masks_path
           A_						       =   Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
           with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"""		,					"""r"""							) as f:
                  A_						       =   json.loads(f.read()							)

           A_						       =   {"""file_name""": """000000039769.png""", """image_id""": 39769, """segments_info""": target}

           A_						       =   pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic"""							)

           # encode them
           A_						       =   DetaImageProcessor(format="""coco_panoptic"""							)
           A_						       =   image_processing(images=UpperCamelCase__		,					annotations=UpperCamelCase__		,					masks_path=UpperCamelCase__		,					return_tensors="""pt"""							)

           # verify pixel values
           A_						       =   torch.Size([1, 3, 800, 1066]							)
           self.assertEqual(encoding["""pixel_values"""].shape		,					UpperCamelCase__							)

           A_						       =   torch.tensor([0.2796, 0.3138, 0.3481]							)
           self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3]		,					UpperCamelCase__		,					atol=1e-4							)							)

           # verify area
           A_						       =   torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""]		,					UpperCamelCase__							)							)
           # verify boxes
           A_						       =   torch.Size([6, 4]							)
           self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape		,					UpperCamelCase__							)
           A_						       =   torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0]		,					UpperCamelCase__		,					atol=1e-3							)							)
           # verify image_id
           A_						       =   torch.tensor([39769]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""]		,					UpperCamelCase__							)							)
           # verify is_crowd
           A_						       =   torch.tensor([0, 0, 0, 0, 0, 0]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""]		,					UpperCamelCase__							)							)
           # verify class_labels
           A_						       =   torch.tensor([17, 17, 63, 75, 75, 93]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""]		,					UpperCamelCase__							)							)
           # verify masks
           A_						       =   822873
           self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item()		,					UpperCamelCase__							)
           # verify orig_size
           A_						       =   torch.tensor([480, 640]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""]		,					UpperCamelCase__							)							)
           # verify size
           A_						       =   torch.tensor([800, 1066]							)
           self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""]		,					UpperCamelCase__							)							)



'''simple docstring'''







from math import pow
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							UpperCAmelCase__,							)      ->      tuple[int, int]:
       if current_sum == needed_sum:
              # If the sum of the powers is equal to needed_sum, then we have a solution.
              solutions_count += 1
              return current_sum, solutions_count

       A_						       =   int(pow(UpperCAmelCase__,							UpperCAmelCase__					)					)
       if current_sum + i_to_n <= needed_sum:
              # If the sum of the powers is less than needed_sum, then continue adding powers.
              current_sum += i_to_n
              A_       ,      A_						       =   backtrack(
                  UpperCAmelCase__,							UpperCAmelCase__,							current_number + 1,							UpperCAmelCase__,							UpperCAmelCase__					)
              current_sum -= i_to_n
       if i_to_n < needed_sum:
              # If the power of i is less than needed_sum, then try with the next power.
              A_       ,      A_						       =   backtrack(
                  UpperCAmelCase__,							UpperCAmelCase__,							current_number + 1,							UpperCAmelCase__,							UpperCAmelCase__					)
       return current_sum, solutions_count
def    UpperCAmelCase__     (   UpperCAmelCase__,							UpperCAmelCase__					)      ->      int:
       if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10):
              raise ValueError(
                  """Invalid input\n"""
                  """needed_sum must be between 1 and 1000, power between 2 and 10."""					)

       return backtrack(UpperCAmelCase__,							UpperCAmelCase__,							1,							0,							0					)[1]  # Return the solutions_count


if __name__ == "__main__":
      import doctest

      doctest.testmod()
