



"""simple docstring"""
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 					a	:



     @staticmethod
     def 	lowerCamelCase__       (						*lowerCAmelCase :					Union[str, Any]       ,		**lowerCAmelCase :					str		)     ->					int:


        '''simple docstring'''




        pass
@is_pipeline_test
@require_torch
@require_vision
class 					a	(  unittest.TestCase       ):
  UpperCamelCase	:				Tuple     						=					MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING



  def 	lowerCamelCase__       (						self :					Any       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Tuple       ,		lowerCAmelCase :					Tuple		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=pipeline("""visual-question-answering"""       ,		model="""hf-internal-testing/tiny-vilt-random-vqa"""		)
     SCREAMING_SNAKE_CASE_: List[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 	lowerCamelCase__       (						self :					Union[str, Any]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					Any		)     ->					Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[Any]     			=vqa_pipeline(lowerCAmelCase       ,		top_k=1		)
     self.assertEqual(
         lowerCAmelCase       ,		[
             [{"""score""": ANY(lowerCAmelCase		), """answer""": ANY(lowerCAmelCase		)}],
             [{"""score""": ANY(lowerCAmelCase		), """answer""": ANY(lowerCAmelCase		)}],
         ]       ,		)



  @require_torch
  def 	lowerCamelCase__       (						self :					Any		)     ->					List[Any]:


     '''simple docstring'''




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

     SCREAMING_SNAKE_CASE_: int     			=vqa_pipeline(image=lowerCAmelCase       ,		question="""How many cats are there?"""       ,		top_k=2		)
     self.assertEqual(
         lowerCAmelCase       ,		[{"""score""": ANY(lowerCAmelCase		), """answer""": ANY(lowerCAmelCase		)}, {"""score""": ANY(lowerCAmelCase		), """answer""": ANY(lowerCAmelCase		)}]		)

     SCREAMING_SNAKE_CASE_: List[str]     			=vqa_pipeline({"""image""": image, """question""": question}       ,		top_k=2		)
     self.assertEqual(
         lowerCAmelCase       ,		[{"""score""": ANY(lowerCAmelCase		), """answer""": ANY(lowerCAmelCase		)}, {"""score""": ANY(lowerCAmelCase		), """answer""": ANY(lowerCAmelCase		)}]		)



  @slow
  @require_torch
  def 	lowerCamelCase__       (						self :					Dict		)     ->					int:


     '''simple docstring'''




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

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=vqa_pipeline(image=lowerCAmelCase       ,		question=lowerCAmelCase       ,		top_k=2		)
     self.assertEqual(
         nested_simplify(lowerCAmelCase       ,		decimals=4		)       ,		[{"""score""": 0.8_7_9_9, """answer""": """2"""}, {"""score""": 0.2_9_6, """answer""": """1"""}]		)

     SCREAMING_SNAKE_CASE_: Optional[int]     			=vqa_pipeline({"""image""": image, """question""": question}       ,		top_k=2		)
     self.assertEqual(
         nested_simplify(lowerCAmelCase       ,		decimals=4		)       ,		[{"""score""": 0.8_7_9_9, """answer""": """2"""}, {"""score""": 0.2_9_6, """answer""": """1"""}]		)

     SCREAMING_SNAKE_CASE_: Optional[int]     			=vqa_pipeline(
         [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]       ,		top_k=2		)
     self.assertEqual(
         nested_simplify(lowerCAmelCase       ,		decimals=4		)       ,		[[{"""score""": 0.8_7_9_9, """answer""": """2"""}, {"""score""": 0.2_9_6, """answer""": """1"""}]] * 2       ,		)





  @require_tf
  @unittest.skip("""Visual question answering not implemented in TF"""		)
  def 	lowerCamelCase__       (						self :					Dict		)     ->					str:


     '''simple docstring'''




     pass








"""simple docstring"""
from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map





def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=[]
   SCREAMING_SNAKE_CASE_: List[str]     			=[]
   SCREAMING_SNAKE_CASE_: Any     			=[]

   for rt in rc.restypes:
      SCREAMING_SNAKE_CASE_: Optional[int]     			=rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
      restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names] )
      SCREAMING_SNAKE_CASE_: Any     			={name: i for i, name in enumerate(lowercase )}
      restype_atomaa_to_atomaa_list.append(
          [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types] )

      restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names] )

   # Add dummy mapping for restype 'UNK'
   restype_atomaa_to_atomaa_list.append([0] * 14 )
   restype_atomaa_to_atomaa_list.append([0] * 37 )
   restype_atomaa_mask_list.append([0.0] * 14 )

   SCREAMING_SNAKE_CASE_: Union[str, Any]     			=torch.tensor(
       lowercase							,			dtype=torch.intaa							,			device=protein["""aatype"""].device							,			)
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=torch.tensor(
       lowercase							,			dtype=torch.intaa							,			device=protein["""aatype"""].device							,			)
   SCREAMING_SNAKE_CASE_: List[str]     			=torch.tensor(
       lowercase							,			dtype=torch.floataa							,			device=protein["""aatype"""].device							,			)
   SCREAMING_SNAKE_CASE_: Optional[Any]     			=protein["""aatype"""].to(torch.long )

   # create the mapping for (residx, atom14) --> atom37, i.e. an array
   # with shape (num_res, 14) containing the atom37 indices for this protein
   SCREAMING_SNAKE_CASE_: List[str]     			=restype_atomaa_to_atomaa[protein_aatype]
   SCREAMING_SNAKE_CASE_: Any     			=restype_atomaa_mask[protein_aatype]

   SCREAMING_SNAKE_CASE_: Tuple     			=residx_atomaa_mask
   SCREAMING_SNAKE_CASE_: Dict     			=residx_atomaa_to_atomaa.long()

   # create the gather indices for mapping back
   SCREAMING_SNAKE_CASE_: Dict     			=restype_atomaa_to_atomaa[protein_aatype]
   SCREAMING_SNAKE_CASE_: Optional[int]     			=residx_atomaa_to_atomaa.long()

   # create the corresponding mask
   SCREAMING_SNAKE_CASE_: Optional[int]     			=torch.zeros([21, 37]							,			dtype=torch.floataa							,			device=protein["""aatype"""].device )
   for restype, restype_letter in enumerate(rc.restypes ):
      SCREAMING_SNAKE_CASE_: int     			=rc.restype_atoa[restype_letter]
      SCREAMING_SNAKE_CASE_: Any     			=rc.residue_atoms[restype_name]
      for atom_name in atom_names:
         SCREAMING_SNAKE_CASE_: Optional[int]     			=rc.atom_order[atom_name]
         SCREAMING_SNAKE_CASE_: Dict     			=1

   SCREAMING_SNAKE_CASE_: List[str]     			=restype_atomaa_mask[protein_aatype]
   SCREAMING_SNAKE_CASE_: List[Any]     			=residx_atomaa_mask

   return protein





def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: Any     			=tree_map(lambda lowercase : torch.tensor(lowercase							,			device=batch["""aatype"""].device )							,			lowercase							,			np.ndarray )
   SCREAMING_SNAKE_CASE_: int     			=tensor_tree_map(lambda lowercase : np.array(lowercase )							,			make_atomaa_masks(lowercase ) )
   return out



