






'''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					,   __a					,   __a=7					,   __a=3					,   __a=3_0					,   __a=4_0_0					,   __a=True					,   __a=None					,   __a=True					,   __a=[0.5, 0.5, 0.5]					,   __a=[0.5, 0.5, 0.5]					,   __a=True					,   __a=1 / 2_5_5					,   __a=True					,   )			->      Optional[int]:
      """simple docstring"""






      __snake_case				:      Union[str, Any]     							= size if size is not None else {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3}
      __snake_case				:      Tuple     							= parent
      __snake_case				:      Any     							= batch_size
      __snake_case				:      Union[str, Any]     							= num_channels
      __snake_case				:      str     							= min_resolution
      __snake_case				:      Tuple     							= max_resolution
      __snake_case				:      List[str]     							= do_resize
      __snake_case				:      int     							= size
      __snake_case				:      Optional[Any]     							= do_normalize
      __snake_case				:      Any     							= image_mean
      __snake_case				:      Any     							= image_std
      __snake_case				:      Optional[Any]     							= do_rescale
      __snake_case				:      Optional[Any]     							= rescale_factor
      __snake_case				:      List[str]     							= do_pad







   def     SCREAMING_SNAKE_CASE__					(self)			->      Any:
      """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     SCREAMING_SNAKE_CASE__					(self					,   __a					,   __a=False)			->      Any:
      """simple docstring"""






      if not batched:
         __snake_case				:      List[str]     							= image_inputs[0]
         if isinstance(__a					,   Image.Image):
            __snake_case				:      Tuple     							= image.size
         else:
            __snake_case				:      str     							= image.shape[1], image.shape[2]
         if w < h:
            __snake_case				:      List[Any]     							= int(self.size['shortest_edge'] * h / w)
            __snake_case				:      List[Any]     							= self.size['shortest_edge']
         elif w > h:
            __snake_case				:      Optional[Any]     							= self.size['shortest_edge']
            __snake_case				:      List[str]     							= int(self.size['shortest_edge'] * w / h)
         else:
            __snake_case				:      Any     							= self.size['shortest_edge']
            __snake_case				:      str     							= self.size['shortest_edge']

      else:
         __snake_case				:      List[Any]     							= []
         for image in image_inputs:
            __snake_case				:      List[Any]     							= self.get_expected_values([image])
            expected_values.append((expected_height, expected_width))
         __snake_case				:      Optional[Any]     							= max(__a					,   key=lambda __a: item[0])[0]
         __snake_case				:      int     							= max(__a					,   key=lambda __a: item[1])[1]

      return expected_height, expected_width




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







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      __snake_case				:      Optional[Any]     							= DetaImageProcessingTester(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)			->      Optional[int]:
      """simple docstring"""






      __snake_case				:      str     							= self.image_processing_class(**self.image_processor_dict)
      self.assertTrue(hasattr(__a					,   'image_mean'))
      self.assertTrue(hasattr(__a					,   'image_std'))
      self.assertTrue(hasattr(__a					,   'do_normalize'))
      self.assertTrue(hasattr(__a					,   'do_resize'))
      self.assertTrue(hasattr(__a					,   'do_rescale'))
      self.assertTrue(hasattr(__a					,   'do_pad'))
      self.assertTrue(hasattr(__a					,   'size'))







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      __snake_case				:      List[Any]     							= self.image_processing_class.from_dict(self.image_processor_dict)
      self.assertEqual(image_processor.size					,   {'shortest_edge': 1_8, 'longest_edge': 1_3_3_3})
      self.assertEqual(image_processor.do_pad					,   __a)







   def     SCREAMING_SNAKE_CASE__					(self)			->      List[str]:
      """simple docstring"""






      pass







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      __snake_case				:      Optional[int]     							= self.image_processing_class(**self.image_processor_dict)
      # create random PIL images
      __snake_case				:      Dict     							= prepare_image_inputs(self.image_processor_tester					,   equal_resolution=__a)
      for image in image_inputs:
         self.assertIsInstance(__a					,   Image.Image)

      # Test not batched input
      __snake_case				:      List[str]     							= image_processing(image_inputs[0]					,   return_tensors='pt').pixel_values

      __snake_case				:      Any     							= self.image_processor_tester.get_expected_values(__a)

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

      # Test batched
      __snake_case				:      List[Any]     							= self.image_processor_tester.get_expected_values(__a					,   batched=__a)

      __snake_case				:      List[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,
              expected_height,
              expected_width,
          )					,   )







   def     SCREAMING_SNAKE_CASE__					(self)			->      Tuple:
      """simple docstring"""






      __snake_case				:      Union[str, Any]     							= self.image_processing_class(**self.image_processor_dict)
      # create random numpy tensors
      __snake_case				:      List[str]     							= 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
      __snake_case				:      str     							= image_processing(image_inputs[0]					,   return_tensors='pt').pixel_values

      __snake_case				:      List[str]     							= self.image_processor_tester.get_expected_values(__a)

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

      # Test batched
      __snake_case				:      Any     							= image_processing(__a					,   return_tensors='pt').pixel_values

      __snake_case				:      List[str]     							= self.image_processor_tester.get_expected_values(__a					,   batched=__a)

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







   def     SCREAMING_SNAKE_CASE__					(self)			->      List[str]:
      """simple docstring"""






      __snake_case				:      str     							= self.image_processing_class(**self.image_processor_dict)
      # create random PyTorch tensors
      __snake_case				:      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
      __snake_case				:      List[str]     							= image_processing(image_inputs[0]					,   return_tensors='pt').pixel_values

      __snake_case				:      Optional[Any]     							= self.image_processor_tester.get_expected_values(__a)

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

      # Test batched
      __snake_case				:      Any     							= image_processing(__a					,   return_tensors='pt').pixel_values

      __snake_case				:      str     							= self.image_processor_tester.get_expected_values(__a					,   batched=__a)

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







   @slow
   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      __snake_case				:      Optional[int]     							= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
      with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'					,   'r') as f:
         __snake_case				:      Optional[int]     							= json.loads(f.read())

      __snake_case				:      str     							= {'image_id': 3_9_7_6_9, 'annotations': target}

      # encode them
      __snake_case				:      List[Any]     							= DetaImageProcessor()
      __snake_case				:      Optional[Any]     							= image_processing(images=__a					,   annotations=__a					,   return_tensors='pt')

      # verify pixel values
      __snake_case				:      Union[str, Any]     							= torch.Size([1, 3, 8_0_0, 1_0_6_6])
      self.assertEqual(encoding['pixel_values'].shape					,   __a)

      __snake_case				:      List[str]     							= torch.tensor([0.2_796, 0.3_138, 0.3_481])
      self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]					,   __a					,   atol=1E-4))

      # verify area
      __snake_case				:      Optional[int]     							= torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8])
      self.assertTrue(torch.allclose(encoding['labels'][0]['area']					,   __a))
      # verify boxes
      __snake_case				:      Any     							= torch.Size([6, 4])
      self.assertEqual(encoding['labels'][0]['boxes'].shape					,   __a)
      __snake_case				:      str     							= torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215])
      self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]					,   __a					,   atol=1E-3))
      # verify image_id
      __snake_case				:      List[str]     							= torch.tensor([3_9_7_6_9])
      self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']					,   __a))
      # verify is_crowd
      __snake_case				:      Optional[Any]     							= torch.tensor([0, 0, 0, 0, 0, 0])
      self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']					,   __a))
      # verify class_labels
      __snake_case				:      Optional[Any]     							= torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7])
      self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']					,   __a))
      # verify orig_size
      __snake_case				:      Dict     							= torch.tensor([4_8_0, 6_4_0])
      self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']					,   __a))
      # verify size
      __snake_case				:      Dict     							= torch.tensor([8_0_0, 1_0_6_6])
      self.assertTrue(torch.allclose(encoding['labels'][0]['size']					,   __a))







   @slow
   def     SCREAMING_SNAKE_CASE__					(self)			->      Dict:
      """simple docstring"""






      __snake_case				:      Tuple     							= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
      with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'					,   'r') as f:
         __snake_case				:      List[Any]     							= json.loads(f.read())

      __snake_case				:      List[str]     							= {'file_name': '000000039769.png', 'image_id': 3_9_7_6_9, 'segments_info': target}

      __snake_case				:      int     							= pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic')

      # encode them
      __snake_case				:      Union[str, Any]     							= DetaImageProcessor(format='coco_panoptic')
      __snake_case				:      Dict     							= image_processing(images=__a					,   annotations=__a					,   masks_path=__a					,   return_tensors='pt')

      # verify pixel values
      __snake_case				:      List[Any]     							= torch.Size([1, 3, 8_0_0, 1_0_6_6])
      self.assertEqual(encoding['pixel_values'].shape					,   __a)

      __snake_case				:      List[str]     							= torch.tensor([0.2_796, 0.3_138, 0.3_481])
      self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3]					,   __a					,   atol=1E-4))

      # verify area
      __snake_case				:      Dict     							= torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7])
      self.assertTrue(torch.allclose(encoding['labels'][0]['area']					,   __a))
      # verify boxes
      __snake_case				:      Tuple     							= torch.Size([6, 4])
      self.assertEqual(encoding['labels'][0]['boxes'].shape					,   __a)
      __snake_case				:      Tuple     							= torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625])
      self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0]					,   __a					,   atol=1E-3))
      # verify image_id
      __snake_case				:      Dict     							= torch.tensor([3_9_7_6_9])
      self.assertTrue(torch.allclose(encoding['labels'][0]['image_id']					,   __a))
      # verify is_crowd
      __snake_case				:      Tuple     							= torch.tensor([0, 0, 0, 0, 0, 0])
      self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd']					,   __a))
      # verify class_labels
      __snake_case				:      Optional[Any]     							= torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3])
      self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels']					,   __a))
      # verify masks
      __snake_case				:      Optional[int]     							= 8_2_2_8_7_3
      self.assertEqual(encoding['labels'][0]['masks'].sum().item()					,   __a)
      # verify orig_size
      __snake_case				:      Optional[int]     							= torch.tensor([4_8_0, 6_4_0])
      self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size']					,   __a))
      # verify size
      __snake_case				:      Tuple     							= torch.tensor([8_0_0, 1_0_6_6])
      self.assertTrue(torch.allclose(encoding['labels'][0]['size']					,   __a))







'''simple docstring'''






import contextlib
import importlib
import io
import unittest

import transformers

# Try to import everything from transformers to ensure every object can be loaded.
from transformers import *  # noqa F406
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch
from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available


if is_torch_available():
      from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification

if is_tf_available():
      from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification

if is_flax_available():
      from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification


__A    	=   DUMMY_UNKNOWN_IDENTIFIER
# An actual model hosted on huggingface.co

__A    	=   '''main'''
# Default branch name
__A    	=   '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2'''
# One particular commit (not the top of `main`)
__A    	=   '''aaaaaaa'''
# This commit does not exist, so we should 404.

__A    	=   '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684'''
# Sha-1 of config.json on the top of `main`, for checking purposes
__A    	=   '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3'''




@contextlib.contextmanager
def        _SCREAMING_SNAKE_CASE  (				)    -> List[Any]:







   """simple docstring"""
   print('Welcome!'  )
   yield
   print('Bye!'  )




@contextlib.contextmanager
def        _SCREAMING_SNAKE_CASE  (				)    -> Optional[Any]:







   """simple docstring"""
   print('Bonjour!'  )
   yield
   print('Au revoir!'  )




class a_    (    unittest.TestCase							):







   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      assert transformers.__spec__ is not None
      assert importlib.util.find_spec('transformers') is not None




class a_    (    unittest.TestCase							):







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      int:
      """simple docstring"""






      with ContextManagers([]):
         print('Transformers are awesome!')
      # The print statement adds a new line at the end of the output
      self.assertEqual(mock_stdout.getvalue()					,   'Transformers are awesome!\n')







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      List[str]:
      """simple docstring"""






      with ContextManagers([context_en()]):
         print('Transformers are awesome!')
      # The output should be wrapped with an English welcome and goodbye
      self.assertEqual(mock_stdout.getvalue()					,   'Welcome!\nTransformers are awesome!\nBye!\n')







   @unittest.mock.patch('sys.stdout'					,   new_callable=io.StringIO)
   def     SCREAMING_SNAKE_CASE__					(self					,   __a)			->      Tuple:
      """simple docstring"""






      with ContextManagers([context_fr(), context_en()]):
         print('Transformers are awesome!')
      # The output should be wrapped with an English and French welcome and goodbye
      self.assertEqual(mock_stdout.getvalue()					,   'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n')







   @require_torch
   def     SCREAMING_SNAKE_CASE__					(self)			->      Union[str, Any]:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   ['labels'])
      self.assertEqual(find_labels(__a)					,   ['labels', 'next_sentence_label'])
      self.assertEqual(find_labels(__a)					,   ['start_positions', 'end_positions'])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   ['labels'])







   @require_tf
   def     SCREAMING_SNAKE_CASE__					(self)			->      List[Any]:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   ['labels'])
      self.assertEqual(find_labels(__a)					,   ['labels', 'next_sentence_label'])
      self.assertEqual(find_labels(__a)					,   ['start_positions', 'end_positions'])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   ['labels'])







   @require_flax
   def     SCREAMING_SNAKE_CASE__					(self)			->      int:
      """simple docstring"""






      self.assertEqual(find_labels(__a)					,   [])
      self.assertEqual(find_labels(__a)					,   [])
      self.assertEqual(find_labels(__a)					,   [])




      class a_    (    UpperCamelCase_							):
         pass


      self.assertEqual(find_labels(__a)					,   [])