

'''simple docstring'''






from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING

lowerCAmelCase__   		=      logging.get_logger(__name__)






@add_end_docstrings(lowerCamelCase__ )
class      lowercase_      (lowerCamelCase__ ):




  """simple docstring"""




  def __init__( self  :	Tuple   ,*lowercase__  :	Optional[int]   ,**lowercase__  :	List[str]     ):
   super().__init__(*lowercase__   ,**lowercase__     )
   self.check_model_type(lowercase__     )






  def    SCREAMING_SNAKE_CASE ( self  :	str   ,lowercase__  :	List[Any]=None   ,lowercase__  :	Optional[int]=None   ,lowercase__  :	Tuple=None   ,**lowercase__  :	List[str]     ):
   __lowercase    ,      __lowercase				    =					{}, {}
   if padding is not None:
    __lowercase				    =					padding
   if truncation is not None:
    __lowercase				    =					truncation
   if top_k is not None:
    __lowercase				    =					top_k
   return preprocess_params, {}, postprocess_params






  def __call__( self  :	List[Any]   ,lowercase__  :	Union["Image.Image", str]   ,lowercase__  :	str = None   ,**lowercase__  :	Any     ):
   if isinstance(lowercase__   ,(Image.Image, str)     ) and isinstance(lowercase__   ,lowercase__     ):
    __lowercase				    =					{'''image''': image, '''question''': question}
   else:
    __lowercase				    =					image
   __lowercase				    =					super().__call__(lowercase__   ,**lowercase__     )
   return results






  def    SCREAMING_SNAKE_CASE ( self  :	Any   ,lowercase__  :	Optional[int]   ,lowercase__  :	Optional[int]=False   ,lowercase__  :	List[str]=False     ):
   __lowercase				    =					load_image(inputs['''image''']     )
   __lowercase				    =					self.tokenizer(
       inputs['''question''']   ,return_tensors=self.framework   ,padding=lowercase__   ,truncation=lowercase__     )
   __lowercase				    =					self.image_processor(images=lowercase__   ,return_tensors=self.framework     )
   model_inputs.update(lowercase__     )
   return model_inputs






  def    SCREAMING_SNAKE_CASE ( self  :	Union[str, Any]   ,lowercase__  :	List[str]     ):
   __lowercase				    =					self.model(**lowercase__     )
   return model_outputs






  def    SCREAMING_SNAKE_CASE ( self  :	Dict   ,lowercase__  :	str   ,lowercase__  :	Any=5     ):
   if top_k > self.model.config.num_labels:
    __lowercase				    =					self.model.config.num_labels

   if self.framework == "pt":
    __lowercase				    =					model_outputs.logits.sigmoid()[0]
    __lowercase    ,      __lowercase				    =					probs.topk(lowercase__     )
   else:
    raise ValueError(F"Unsupported framework: {self.framework}"     )

   __lowercase				    =					scores.tolist()
   __lowercase				    =					ids.tolist()
   return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(lowercase__   ,lowercase__     )]






"""simple docstring"""







import unittest

from transformers.utils.backbone_utils import (
    BackboneMixin,
    get_aligned_output_features_output_indices,
    verify_out_features_out_indices,
)






class       UpperCamelCase__			(   unittest.TestCase      ):

			"""simple docstring"""


			def   snake_case__	(      self		)      ->	Dict:
				A__											=					["a", "b", "c"]

				# Defaults to last layer if both are None
				A__							,							A__											=					get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	["c"]		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	[2]		)

				# Out indices set to match out features
				A__							,							A__											=					get_aligned_output_features_output_indices(["a", "c"]						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	["a", "c"]		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	[0, 2]		)

				# Out features set to match out indices
				A__							,							A__											=					get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE__						,	[0, 2]						,	SCREAMING_SNAKE_CASE__		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	["a", "c"]		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	[0, 2]		)

				# Out features selected from negative indices
				A__							,							A__											=					get_aligned_output_features_output_indices(SCREAMING_SNAKE_CASE__						,	[-3, -1]						,	SCREAMING_SNAKE_CASE__		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	["a", "c"]		)
				self.assertEqual(SCREAMING_SNAKE_CASE__						,	[-3, -1]		)


			def   snake_case__	(      self		)      ->	Dict:
				# Stage names must be set
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(["a", "b"]						,	(0, 1)						,	SCREAMING_SNAKE_CASE__		)

				# Out features must be a list
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(("a", "b")						,	(0, 1)						,	["a", "b"]		)

				# Out features must be a subset of stage names
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(["a", "b"]						,	(0, 1)						,	["a"]		)

				# Out indices must be a list or tuple
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(SCREAMING_SNAKE_CASE__						,	0						,	["a", "b"]		)

				# Out indices must be a subset of stage names
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(SCREAMING_SNAKE_CASE__						,	(0, 1)						,	["a"]		)

				# Out features and out indices must be the same length
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(["a", "b"]						,	(0,)						,	["a", "b", "c"]		)

				# Out features should match out indices
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(["a", "b"]						,	(0, 2)						,	["a", "b", "c"]		)

				# Out features and out indices should be in order
				with self.assertRaises(SCREAMING_SNAKE_CASE__		):
					verify_out_features_out_indices(["b", "a"]						,	(0, 1)						,	["a", "b"]		)

				# Check passes with valid inputs
				verify_out_features_out_indices(["a", "b", "d"]						,	(0, 1, -1)						,	["a", "b", "c", "d"]		)







			def   snake_case__	(      self		)      ->	List[Any]:
				A__											=					BackboneMixin()

				A__											=					["a", "b", "c"]
				A__											=					["a", "c"]
				A__											=					[0, 2]

				# Check that the output features and indices are set correctly
				self.assertEqual(backbone.out_features						,	["a", "c"]		)
				self.assertEqual(backbone.out_indices						,	[0, 2]		)

				# Check out features and indices are updated correctly
				A__											=					["a", "b"]
				self.assertEqual(backbone.out_features						,	["a", "b"]		)
				self.assertEqual(backbone.out_indices						,	[0, 1]		)

				A__											=					[-3, -1]
				self.assertEqual(backbone.out_features						,	["a", "c"]		)
				self.assertEqual(backbone.out_indices						,	[-3, -1]		)




