





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 YolosImageProcessor





class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       def __init__(    self	:	List[Any]						,__A	:	Union[str, Any]						,__A	:	Tuple=7						,__A	:	List[Any]=3						,__A	:	int=30						,__A	:	int=400						,__A	:	Any=True						,__A	:	Dict=None						,__A	:	Any=True						,__A	:	Dict=[0.5, 0.5, 0.5]						,__A	:	Union[str, Any]=[0.5, 0.5, 0.5]						,__A	:	int=True						,__A	:	List[str]=1 / 255						,__A	:	List[Any]=True						,)						->					Union[str, Any]:
         # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
         _lowercase							= size if size is not None else {'shortest_edge': 18, 'longest_edge': 1333}
         _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_rescale
         _lowercase							= rescale_factor
         _lowercase							= do_pad







       def    __UpperCAmelCase (    self	:	Dict  )						->					int:
         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    __UpperCAmelCase (    self	:	Any						,__A	:	Union[str, Any]						,__A	:	Union[str, Any]=False  )						->					Dict:
         if not batched:
           _lowercase							= image_inputs[0]
           if isinstance(__A						,Image.Image  ):
             _lowercase						,		_lowercase							= image.size
           else:
             _lowercase						,		_lowercase							= image.shape[1], image.shape[2]
           if w < h:
             _lowercase							= int(self.size['shortest_edge'] * h / w  )
             _lowercase							= self.size['shortest_edge']
           elif w > h:
             _lowercase							= self.size['shortest_edge']
             _lowercase							= int(self.size['shortest_edge'] * w / h  )
           else:
             _lowercase							= self.size['shortest_edge']
             _lowercase							= self.size['shortest_edge']

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

         return expected_height, expected_width





@require_torch
@require_vision
class 				A_				(      UpperCAmelCase					,	unittest.TestCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : int      =  YolosImageProcessor if is_vision_available() else None







       def    __UpperCAmelCase (    self	:	Optional[int]  )						->					Dict:
         _lowercase							= YolosImageProcessingTester(self  )







       @property
       def    __UpperCAmelCase (    self	:	Any  )						->					int:
         return self.image_processor_tester.prepare_image_processor_dict()







       def    __UpperCAmelCase (    self	:	List[str]  )						->					Any:
         _lowercase							= 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						,'size'  )  )







       def    __UpperCAmelCase (    self	:	str  )						->					Dict:
         _lowercase							= 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						,__A  )

         _lowercase							= self.image_processing_class.from_dict(
             self.image_processor_dict						,size=42						,max_size=84						,pad_and_return_pixel_mask=__A  )
         self.assertEqual(image_processor.size						,{'shortest_edge': 42, 'longest_edge': 84}  )
         self.assertEqual(image_processor.do_pad						,__A  )







       def    __UpperCAmelCase (    self	:	str  )						->					str:
         pass







       def    __UpperCAmelCase (    self	:	str  )						->					List[Any]:
         # 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=__A  )
         for image in image_inputs:
           self.assertIsInstance(__A						,Image.Image  )

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

         _lowercase						,		_lowercase							= 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
         _lowercase						,		_lowercase							= self.image_processor_tester.get_expected_values(__A						,batched=__A  )

         _lowercase							= 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    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					Optional[Any]:
         # 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=__A						,numpify=__A  )
         for image in image_inputs:
           self.assertIsInstance(__A						,np.ndarray  )

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

         _lowercase						,		_lowercase							= 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
         _lowercase							= image_processing(__A						,return_tensors='pt'  ).pixel_values

         _lowercase						,		_lowercase							= 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    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					List[Any]:
         # 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=__A						,torchify=__A  )
         for image in image_inputs:
           self.assertIsInstance(__A						,torch.Tensor  )

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

         _lowercase						,		_lowercase							= 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
         _lowercase							= image_processing(__A						,return_tensors='pt'  ).pixel_values

         _lowercase						,		_lowercase							= 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    __UpperCAmelCase (    self	:	Optional[Any]  )						->					List[Any]:
         # Initialize image_processings
         _lowercase							= self.image_processing_class(**self.image_processor_dict  )
         _lowercase							= self.image_processing_class(do_resize=__A						,do_normalize=__A						,do_rescale=__A  )
         # create random PyTorch tensors
         _lowercase							= prepare_image_inputs(self.image_processor_tester						,equal_resolution=__A						,torchify=__A  )
         for image in image_inputs:
           self.assertIsInstance(__A						,torch.Tensor  )

         # Test whether the method "pad" and calling the image processor return the same tensors
         _lowercase							= image_processing_a.pad(__A						,return_tensors='pt'  )
         _lowercase							= image_processing_a(__A						,return_tensors='pt'  )

         self.assertTrue(
             torch.allclose(encoded_images_with_method['pixel_values']						,encoded_images['pixel_values']						,atol=1e-4  )  )







       @slow
       def    __UpperCAmelCase (    self	:	List[Any]  )						->					Union[str, Any]:
         # prepare image and target
         _lowercase							= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
         with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt'						,'r'  ) as f:
           _lowercase							= json.loads(f.read()  )

         _lowercase							= {'image_id': 3_9769, 'annotations': target}

         # encode them
         _lowercase							= YolosImageProcessor.from_pretrained('hustvl/yolos-small'  )
         _lowercase							= image_processing(images=__A						,annotations=__A						,return_tensors='pt'  )

         # verify pixel values
         _lowercase							= torch.Size([1, 3, 800, 1066]  )
         self.assertEqual(encoding['pixel_values'].shape						,__A  )

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

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







       @slow
       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					Dict:
         # prepare image, target and masks_path
         _lowercase							= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
         with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'						,'r'  ) as f:
           _lowercase							= json.loads(f.read()  )

         _lowercase							= {'file_name': '000000039769.png', 'image_id': 3_9769, 'segments_info': target}

         _lowercase							= pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic'  )

         # encode them
         _lowercase							= YolosImageProcessor(format='coco_panoptic'  )
         _lowercase							= image_processing(images=__A						,annotations=__A						,masks_path=__A						,return_tensors='pt'  )

         # verify pixel values
         _lowercase							= torch.Size([1, 3, 800, 1066]  )
         self.assertEqual(encoding['pixel_values'].shape						,__A  )

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

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












import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
      import jax
      import jax.numpy as jnp

      from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor





class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       def __init__(    self	:	List[str]						,__A	:	str						,__A	:	Dict=3						,__A	:	str=32						,__A	:	int=3						,__A	:	Union[str, Any]=10						,__A	:	Optional[Any]=[10, 20, 30, 40]						,__A	:	List[str]=[1, 1, 2, 1]						,__A	:	Optional[int]=True						,__A	:	Optional[Any]=True						,__A	:	int="relu"						,__A	:	Union[str, Any]=3						,__A	:	List[Any]=None						,)						->					int:
         _lowercase							= parent
         _lowercase							= batch_size
         _lowercase							= image_size
         _lowercase							= num_channels
         _lowercase							= embeddings_size
         _lowercase							= hidden_sizes
         _lowercase							= depths
         _lowercase							= is_training
         _lowercase							= use_labels
         _lowercase							= hidden_act
         _lowercase							= num_labels
         _lowercase							= scope
         _lowercase							= len(__A  )







       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					Any:
         _lowercase							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

         _lowercase							= self.get_config()

         return config, pixel_values







       def    __UpperCAmelCase (    self	:	Any  )						->					int:
         return RegNetConfig(
             num_channels=self.num_channels						,embeddings_size=self.embeddings_size						,hidden_sizes=self.hidden_sizes						,depths=self.depths						,hidden_act=self.hidden_act						,num_labels=self.num_labels						,image_size=self.image_size						,)







       def    __UpperCAmelCase (    self	:	Tuple						,__A	:	Any						,__A	:	Union[str, Any]  )						->					List[Any]:
         _lowercase							= FlaxRegNetModel(config=__A  )
         _lowercase							= model(__A  )

         # Output shape (b, c, h, w)
         self.parent.assertEqual(
             result.last_hidden_state.shape						,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)						,)







       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	Optional[int]						,__A	:	Dict  )						->					Any:
         _lowercase							= self.num_labels
         _lowercase							= FlaxRegNetForImageClassification(config=__A  )
         _lowercase							= model(__A  )
         self.parent.assertEqual(result.logits.shape						,(self.batch_size, self.num_labels)  )







       def    __UpperCAmelCase (    self	:	Tuple  )						->					Any:
         _lowercase							= self.prepare_config_and_inputs()
         _lowercase						,		_lowercase							= config_and_inputs
         _lowercase							= {'pixel_values': pixel_values}
         return config, inputs_dict





@require_flax
class 				A_				(      UpperCAmelCase					,	unittest.TestCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Tuple      =  (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

       SCREAMING_SNAKE_CASE_      : Union[str, Any]      =  False
       SCREAMING_SNAKE_CASE_      : Any      =  False
       SCREAMING_SNAKE_CASE_      : Union[str, Any]      =  False







       def    __UpperCAmelCase (    self	:	Dict  )						->					None:
         _lowercase							= FlaxRegNetModelTester(self  )
         _lowercase							= ConfigTester(self						,config_class=__A						,has_text_modality=__A  )







       def    __UpperCAmelCase (    self	:	List[str]  )						->					Union[str, Any]:
         self.create_and_test_config_common_properties()
         self.config_tester.create_and_test_config_to_json_string()
         self.config_tester.create_and_test_config_to_json_file()
         self.config_tester.create_and_test_config_from_and_save_pretrained()
         self.config_tester.create_and_test_config_with_num_labels()
         self.config_tester.check_config_can_be_init_without_params()
         self.config_tester.check_config_arguments_init()







       def    __UpperCAmelCase (    self	:	Optional[int]  )						->					Any:
         return







       def    __UpperCAmelCase (    self	:	Dict  )						->					int:
         _lowercase							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__A  )







       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					Any:
         _lowercase							= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__A  )







       @unittest.skip(reason='RegNet does not use inputs_embeds'  )
       def    __UpperCAmelCase (    self	:	List[str]  )						->					Optional[int]:
         pass







       @unittest.skip(reason='RegNet does not support input and output embeddings'  )
       def    __UpperCAmelCase (    self	:	Tuple  )						->					Any:
         pass







       def    __UpperCAmelCase (    self	:	Dict  )						->					List[str]:
         _lowercase						,		_lowercase							= self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           _lowercase							= model_class(__A  )
           _lowercase							= inspect.signature(model.__call__  )
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           _lowercase							= [*signature.parameters.keys()]

           _lowercase							= ['pixel_values']
           self.assertListEqual(arg_names[:1]						,__A  )







       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					List[str]:
         def check_hidden_states_output(__A	:	Optional[Any]						,__A	:	Optional[int]						,__A	:	str  ):
           _lowercase							= model_class(__A  )

           _lowercase							= model(**self._prepare_for_class(__A						,__A  )  )

           _lowercase							= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

           _lowercase							= self.model_tester.num_stages
           self.assertEqual(len(__A  )						,expected_num_stages + 1  )

         _lowercase						,		_lowercase							= self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           _lowercase							= True
           check_hidden_states_output(__A						,__A						,__A  )

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           _lowercase							= True

           check_hidden_states_output(__A						,__A						,__A  )







       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					int:
         _lowercase						,		_lowercase							= self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           with self.subTest(model_class.__name__  ):
             _lowercase							= self._prepare_for_class(__A						,__A  )
             _lowercase							= model_class(__A  )

             @jax.jit
             def model_jitted(__A	:	Any						,**__A	:	Union[str, Any]  ):
               return model(pixel_values=__A						,**__A  )

             with self.subTest('JIT Enabled'  ):
               _lowercase							= model_jitted(**__A  ).to_tuple()

             with self.subTest('JIT Disabled'  ):
               with jax.disable_jit():
                 _lowercase							= model_jitted(**__A  ).to_tuple()

             self.assertEqual(len(__A  )						,len(__A  )  )
             for jitted_output, output in zip(__A						,__A  ):
               self.assertEqual(jitted_output.shape						,output.shape  )

def 							SCREAMING_SNAKE_CASE__       (  )      ->						str:
  _lowercase							= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
  return image







@require_flax
class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       @cached_property
       def    __UpperCAmelCase (    self	:	str  )						->					Any:
         return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'  ) if is_vision_available() else None







       @slow
       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					Any:
         _lowercase							= FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040'  )

         _lowercase							= self.default_image_processor
         _lowercase							= prepare_img()
         _lowercase							= image_processor(images=__A						,return_tensors='np'  )

         _lowercase							= model(**__A  )

         # verify the logits
         _lowercase							= (1, 1000)
         self.assertEqual(outputs.logits.shape						,__A  )

         _lowercase							= jnp.array([-0.4180, -1.5051, -3.4836]  )

         self.assertTrue(jnp.allclose(outputs.logits[0, :3]						,__A						,atol=1e-4  )  )