
import unittest

from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
   from PIL import Image
else:





   class     __UpperCamelCase :






        """simple docstring"""







        @staticmethod
        def  UpperCAmelCase__							(				*_A							:							Tuple     ,						**_A							:							List[str] ):







          """simple docstring"""




          pass





@is_pipeline_test
@require_torch
@require_vision
class     __UpperCamelCase (							unittest.TestCase       ):






     """simple docstring"""







     lowerCAmelCase_							   =			MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING



     def  UpperCAmelCase__							(				self							:							Union[str, Any]     ,						_A							:							List[Any]     ,						_A							:							List[str]     ,						_A							:							Any ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	List[Any]					=		pipeline('''visual-question-answering'''     ,						model='''hf-internal-testing/tiny-vilt-random-vqa''' )
       __SCREAMING_SNAKE_CASE      :	str					=		[
           {
               '''image''': Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ),
               '''question''': '''How many cats are there?''',
           },
           {
               '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''',
               '''question''': '''How many cats are there?''',
           },
       ]
       return vqa_pipeline, examples



     def  UpperCAmelCase__							(				self							:							Any     ,						_A							:							Dict     ,						_A							:							Optional[Any] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	List[Any]					=		vqa_pipeline(_A     ,						top_k=1 )
       self.assertEqual(
           _A     ,						[
               [{'''score''': ANY(_A ), '''answer''': ANY(_A )}],
               [{'''score''': ANY(_A ), '''answer''': ANY(_A )}],
           ]     ,						)



     @require_torch
     def  UpperCAmelCase__							(				self							:							Dict ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Dict					=		pipeline('''visual-question-answering'''     ,						model='''hf-internal-testing/tiny-vilt-random-vqa''' )
       __SCREAMING_SNAKE_CASE      :	Dict					=		'''./tests/fixtures/tests_samples/COCO/000000039769.png'''
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		'''How many cats are there?'''

       __SCREAMING_SNAKE_CASE      :	str					=		vqa_pipeline(image=_A     ,						question='''How many cats are there?'''     ,						top_k=2 )
       self.assertEqual(
           _A     ,						[{'''score''': ANY(_A ), '''answer''': ANY(_A )}, {'''score''': ANY(_A ), '''answer''': ANY(_A )}] )

       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		vqa_pipeline({'''image''': image, '''question''': question}     ,						top_k=2 )
       self.assertEqual(
           _A     ,						[{'''score''': ANY(_A ), '''answer''': ANY(_A )}, {'''score''': ANY(_A ), '''answer''': ANY(_A )}] )



     @slow
     @require_torch
     def  UpperCAmelCase__							(				self							:							List[str] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Any					=		pipeline('''visual-question-answering'''     ,						model='''dandelin/vilt-b32-finetuned-vqa''' )
       __SCREAMING_SNAKE_CASE      :	Any					=		'''./tests/fixtures/tests_samples/COCO/000000039769.png'''
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		'''How many cats are there?'''

       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		vqa_pipeline(image=_A     ,						question=_A     ,						top_k=2 )
       self.assertEqual(
           nested_simplify(_A     ,						decimals=4 )     ,						[{'''score''': 0.87_99, '''answer''': '''2'''}, {'''score''': 0.2_96, '''answer''': '''1'''}] )

       __SCREAMING_SNAKE_CASE      :	Any					=		vqa_pipeline({'''image''': image, '''question''': question}     ,						top_k=2 )
       self.assertEqual(
           nested_simplify(_A     ,						decimals=4 )     ,						[{'''score''': 0.87_99, '''answer''': '''2'''}, {'''score''': 0.2_96, '''answer''': '''1'''}] )

       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		vqa_pipeline(
           [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]     ,						top_k=2 )
       self.assertEqual(
           nested_simplify(_A     ,						decimals=4 )     ,						[[{'''score''': 0.87_99, '''answer''': '''2'''}, {'''score''': 0.2_96, '''answer''': '''1'''}]] * 2     ,						)




     @require_tf
     @unittest.skip('''Visual question answering not implemented in TF''' )
     def  UpperCAmelCase__							(				self							:							str ):







       """simple docstring"""




       pass








'''simple docstring'''



from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


SCREAMING_SNAKE_CASE							=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE							=						{
    'google/bit-50': 'https://huggingface.co/google/bit-50/resolve/main/config.json',
}
class UpperCAmelCase_       (     __A					,							__A					):




      """simple docstring"""




      UpperCamelCase_             =      '''bit'''
      UpperCamelCase_             =      ['''preactivation''', '''bottleneck''']
      UpperCamelCase_             =      ['''SAME''', '''VALID''']






      def __init__(			self      :		Any  ,   UpperCAmelCase      :		Optional[int]=3  ,   UpperCAmelCase      :		Any=64  ,   UpperCAmelCase      :		List[str]=[256, 512, 1024, 2048]  ,   UpperCAmelCase      :		Dict=[3, 4, 6, 3]  ,   UpperCAmelCase      :		List[Any]="preactivation"  ,   UpperCAmelCase      :		Tuple="relu"  ,   UpperCAmelCase      :		Tuple=None  ,   UpperCAmelCase      :		Tuple=32  ,   UpperCAmelCase      :		Optional[int]=0.0  ,   UpperCAmelCase      :		Union[str, Any]=False  ,   UpperCAmelCase      :		Dict=32  ,   UpperCAmelCase      :		Any=1  ,   UpperCAmelCase      :		str=None  ,   UpperCAmelCase      :		Union[str, Any]=None  ,   **UpperCAmelCase      :		str  ,   )	->	Dict:


       '''simple docstring'''

       super().__init__(**UpperCAmelCase		)
       if layer_type not in self.layer_types:
        raise ValueError(f'layer_type={layer_type} is not one of {",".join(self.layer_types		)}'		)
       if global_padding is not None:
        if global_padding.upper() in self.supported_padding:
         lowercase       : Any						=global_padding.upper()
        else:
         raise ValueError(f'Padding strategy {global_padding} not supported'		)
       lowercase       : List[Any]						=num_channels
       lowercase       : List[str]						=embedding_size
       lowercase       : Union[str, Any]						=hidden_sizes
       lowercase       : Union[str, Any]						=depths
       lowercase       : Optional[int]						=layer_type
       lowercase       : Optional[Any]						=hidden_act
       lowercase       : List[str]						=global_padding
       lowercase       : Dict						=num_groups
       lowercase       : Optional[Any]						=drop_path_rate
       lowercase       : Union[str, Any]						=embedding_dynamic_padding
       lowercase       : Any						=output_stride
       lowercase       : Union[str, Any]						=width_factor

       lowercase       : Union[str, Any]						=['''stem'''] + [f'stage{idx}' for idx in range(1  ,   len(UpperCAmelCase		) + 1		)]
       lowercase	,		lowercase       : List[str]						=get_aligned_output_features_output_indices(
           out_features=UpperCAmelCase  ,   out_indices=UpperCAmelCase  ,   stage_names=self.stage_names		)



