


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


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

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

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

@contextlib.contextmanager
def 					lowerCamelCase_ ( )					->	Tuple:







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

@contextlib.contextmanager
def 					lowerCamelCase_ ( )					->	Dict:







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






class        lowerCAmelCase_  (     unittest.TestCase	):






       def   UpperCamelCase						( self   )->      Optional[int]:
            # If the spec is missing, importlib would not be able to import the module dynamically.
            assert transformers.__spec__ is not None
            assert importlib.util.find_spec('transformers'   ) is not None






class        lowerCAmelCase_  (     unittest.TestCase	):






       @unittest.mock.patch('sys.stdout'			,     new_callable=io.StringIO   )
       def   UpperCamelCase						( self			,     _UpperCamelCase   )->      Any:
            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   UpperCamelCase						( self			,     _UpperCamelCase   )->      Optional[int]:
            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   UpperCamelCase						( self			,     _UpperCamelCase   )->      str:
            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   UpperCamelCase						( self   )->      Dict:
            self.assertEqual(find_labels(_UpperCamelCase   )			,     ['labels']   )
            self.assertEqual(find_labels(_UpperCamelCase   )			,     ['labels', 'next_sentence_label']   )
            self.assertEqual(find_labels(_UpperCamelCase   )			,     ['start_positions', 'end_positions']   )






            class        lowerCAmelCase_  (     UpperCAmelCase	):
                   pass






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






       @require_tf
       def   UpperCamelCase						( self   )->      Optional[int]:
            self.assertEqual(find_labels(_UpperCamelCase   )			,     ['labels']   )
            self.assertEqual(find_labels(_UpperCamelCase   )			,     ['labels', 'next_sentence_label']   )
            self.assertEqual(find_labels(_UpperCamelCase   )			,     ['start_positions', 'end_positions']   )






            class        lowerCAmelCase_  (     UpperCAmelCase	):
                   pass






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






       @require_flax
       def   UpperCamelCase						( self   )->      List[Any]:
            # Flax models don't have labels
            self.assertEqual(find_labels(_UpperCamelCase   )			,     []   )
            self.assertEqual(find_labels(_UpperCamelCase   )			,     []   )
            self.assertEqual(find_labels(_UpperCamelCase   )			,     []   )






            class        lowerCAmelCase_  (     UpperCAmelCase	):
                   pass






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









'''simple docstring'''
import unittest

import numpy as np
import requests

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

    from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
    lowerCAmelCase						=					False

if is_vision_available():
    from PIL import Image

    from transformers import PixaStructImageProcessor






class        lowerCAmelCase_  (     unittest.TestCase	):






       def __init__( self			,     _UpperCamelCase			,     _UpperCamelCase=7			,     _UpperCamelCase=3			,     _UpperCamelCase=18			,     _UpperCamelCase=30			,     _UpperCamelCase=400			,     _UpperCamelCase=None			,     _UpperCamelCase=True			,     _UpperCamelCase=True			,     _UpperCamelCase=None			,     )->      Dict:
            _A				=							size if size is not None else {'height': 20, 'width': 20}
            _A				=							parent
            _A				=							batch_size
            _A				=							num_channels
            _A				=							image_size
            _A				=							min_resolution
            _A				=							max_resolution
            _A				=							size
            _A				=							do_normalize
            _A				=							do_convert_rgb
            _A				=							[512, 1024, 2048, 4096]
            _A				=							patch_size if patch_size is not None else {'height': 16, 'width': 16}






       def   UpperCamelCase						( self   )->      Dict:
            return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}






       def   UpperCamelCase						( self   )->      Tuple:
            _A				=							'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg'
            _A				=							Image.open(requests.get(_UpperCamelCase			,     stream=_UpperCamelCase   ).raw   ).convert('RGB'   )
            return raw_image






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11      ,							reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'      ,							)
@require_torch
@require_vision
class        lowerCAmelCase_  (     UpperCAmelCase      ,							unittest.TestCase	):
       __UpperCAmelCase					=PixaStructImageProcessor if is_vision_available() else None






       def   UpperCamelCase						( self   )->      Optional[int]:
            _A				=							PixaStructImageProcessingTester(self   )






       @property
       def   UpperCamelCase						( self   )->      Tuple:
            return self.image_processor_tester.prepare_image_processor_dict()






       def   UpperCamelCase						( self   )->      List[Any]:
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_normalize'   )   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_convert_rgb'   )   )






       def   UpperCamelCase						( self   )->      Any:
            _A				=							self.image_processor_tester.prepare_dummy_image()

            _A				=							self.image_processing_class(**self.image_processor_dict   )
            _A				=							2048

            _A				=							image_processor(_UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   )
            self.assertTrue(torch.allclose(inputs.flattened_patches.mean()			,     torch.tensor(0.0606   )			,     atol=1e-3			,     rtol=1e-3   )   )






       def   UpperCamelCase						( self   )->      int:
            # Initialize image_processor
            _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				=							(
                (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 _A				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






       def   UpperCamelCase						( self   )->      List[str]:
            # Initialize image_processor
            _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				=							(
                (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
                * self.image_processor_tester.num_channels
            ) + 2

            _A				=							True

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 with self.assertRaises(_UpperCamelCase   ):
                      _A				=							image_processor(
                          image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches

                 _A				=							'Hello'

                 _A				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase			,     header_text=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase			,     header_text=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






       def   UpperCamelCase						( self   )->      Optional[int]:
            # Initialize image_processor
            _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   )

            _A				=							(
                (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 _A				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






       def   UpperCamelCase						( self   )->      Union[str, Any]:
            # Initialize image_processor
            _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				=							(
                (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
                * self.image_processor_tester.num_channels
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 _A				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )






@unittest.skipIf(
    not is_torch_greater_or_equal_than_1_11      ,							reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.'      ,							)
@require_torch
@require_vision
class        lowerCAmelCase_  (     UpperCAmelCase      ,							unittest.TestCase	):
       __UpperCAmelCase					=PixaStructImageProcessor if is_vision_available() else None






       def   UpperCamelCase						( self   )->      str:
            _A				=							PixaStructImageProcessingTester(self			,     num_channels=4   )
            _A				=							3






       @property
       def   UpperCamelCase						( self   )->      str:
            return self.image_processor_tester.prepare_image_processor_dict()






       def   UpperCamelCase						( self   )->      Any:
            _A				=							self.image_processing_class(**self.image_processor_dict   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_normalize'   )   )
            self.assertTrue(hasattr(_UpperCamelCase			,     'do_convert_rgb'   )   )






       def   UpperCamelCase						( self   )->      Optional[Any]:
            # Initialize image_processor
            _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				=							(
                (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width'])
                * (self.image_processor_tester.num_channels - 1)
            ) + 2

            for max_patch in self.image_processor_tester.max_patches:
                 # Test not batched input
                 _A				=							image_processor(
                     image_inputs[0]			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (1, max_patch, expected_hidden_dim)			,     )

                 # Test batched
                 _A				=							image_processor(
                     _UpperCamelCase			,     return_tensors='pt'			,     max_patches=_UpperCamelCase   ).flattened_patches
                 self.assertEqual(
                     encoded_images.shape			,     (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim)			,     )





