






'''simple docstring'''







_A	:			List[str]         ='''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'''





def  SCREAMING_SNAKE_CASE_       (UpperCamelCase      )      ->       bytes:
							# Make sure the supplied data is a bytes-like object
							if not isinstance(UpperCamelCase				,			UpperCamelCase      ):
														lowerCamelCase__					:	Dict         =       f'''a bytes-like object is required, not \'{data.__class__.__name__}\''''
														raise TypeError(UpperCamelCase      )

							lowerCamelCase__					:	int         =       """""".join(bin(UpperCamelCase      )[2:].zfill(8      ) for byte in data      )

							lowerCamelCase__					:	int         =       len(UpperCamelCase      ) % 6 != 0

							if padding_needed:
														# The padding that will be added later
														lowerCamelCase__					:	Optional[Any]         =       b"""=""" * ((6 - len(UpperCamelCase      ) % 6) // 2)

														# Append binary_stream with arbitrary binary digits (0's by default) to make its
														# length a multiple of 6.
														binary_stream += "0" * (6 - len(UpperCamelCase      ) % 6)
							else:
														lowerCamelCase__					:	Optional[int]         =       b""""""

							# Encode every 6 binary digits to their corresponding Base64 character
							return (
							    "".join(
							        B64_CHARSET[int(binary_stream[index : index + 6]				,			2      )]
							        for index in range(0				,			len(UpperCamelCase      )				,			6      )      ).encode()
							    + padding
							)





def  SCREAMING_SNAKE_CASE_       (UpperCamelCase      )      ->       bytes:
							# Make sure encoded_data is either a string or a bytes-like object
							if not isinstance(UpperCamelCase				,			UpperCamelCase      ) and not isinstance(UpperCamelCase				,			UpperCamelCase      ):
														lowerCamelCase__					:	int         =       (
														    """argument should be a bytes-like object or ASCII string, """
														    f'''not \'{encoded_data.__class__.__name__}\''''
														)
														raise TypeError(UpperCamelCase      )

							# In case encoded_data is a bytes-like object, make sure it contains only
							# ASCII characters so we convert it to a string object
							if isinstance(UpperCamelCase				,			UpperCamelCase      ):
														try:
																					lowerCamelCase__					:	str         =       encoded_data.decode("""utf-8"""      )
														except UnicodeDecodeError:
																					raise ValueError("""base64 encoded data should only contain ASCII characters"""      )

							lowerCamelCase__					:	Tuple         =       encoded_data.count("""="""      )

							# Check if the encoded string contains non base64 characters
							if padding:
														assert all(
														    char in B64_CHARSET for char in encoded_data[:-padding]      ), "Invalid base64 character(s) found."
							else:
														assert all(
														    char in B64_CHARSET for char in encoded_data      ), "Invalid base64 character(s) found."

							# Check the padding
							assert len(UpperCamelCase      ) % 4 == 0 and padding < 3, "Incorrect padding"

							if padding:
														# Remove padding if there is one
														lowerCamelCase__					:	Any         =       encoded_data[:-padding]

														lowerCamelCase__					:	int         =       """""".join(
														    bin(B64_CHARSET.index(UpperCamelCase      )      )[2:].zfill(6      ) for char in encoded_data      )[: -padding * 2]
							else:
														lowerCamelCase__					:	Tuple         =       """""".join(
														    bin(B64_CHARSET.index(UpperCamelCase      )      )[2:].zfill(6      ) for char in encoded_data      )

							lowerCamelCase__					:	List[Any]         =       [
							    int(binary_stream[index : index + 8]				,			2      )
							    for index in range(0				,			len(UpperCamelCase      )				,			8      )
							]

							return bytes(UpperCamelCase      )


if __name__ == "__main__":
			import doctest

			doctest.testmod()









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

__UpperCAmelCase								=						logging.get_logger(__name__)



@add_end_docstrings(_snake_case			)
class   lowerCamelCase      (_snake_case			):







		'''simple docstring'''



		def __init__(							self				,		*_UpperCamelCase				,		**_UpperCamelCase   )	->							int:
							super().__init__(*_UpperCamelCase				,		**_UpperCamelCase   )
							self.check_model_type(_UpperCamelCase   )



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase=None				,		_UpperCamelCase=None				,		_UpperCamelCase=None				,		**_UpperCamelCase   )	->							List[Any]:
							UpperCAmelCase_       ,  UpperCAmelCase_    :      Tuple            =						{}, {}
							if padding is not None:
												UpperCAmelCase_    :      List[str]            =						padding
							if truncation is not None:
												UpperCAmelCase_    :      Tuple            =						truncation
							if top_k is not None:
												UpperCAmelCase_    :      Dict            =						top_k
							return preprocess_params, {}, postprocess_params



		def __call__(							self				,		_UpperCamelCase				,		_UpperCamelCase = None				,		**_UpperCamelCase   )	->							int:
							if isinstance(_UpperCamelCase				,		(Image.Image, str)   ) and isinstance(_UpperCamelCase				,		_UpperCamelCase   ):
												UpperCAmelCase_    :      Optional[Any]            =						{'image': image, 'question': question}
							else:
												UpperCAmelCase_    :      List[str]            =						image
							UpperCAmelCase_    :      Optional[Any]            =						super().__call__(_UpperCamelCase				,		**_UpperCamelCase   )
							return results



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=False				,		_UpperCamelCase=False   )	->							Optional[Any]:
							UpperCAmelCase_    :      List[Any]            =						load_image(inputs['image']   )
							UpperCAmelCase_    :      Dict            =						self.tokenizer(
							    inputs['question']				,		return_tensors=self.framework				,		padding=_UpperCamelCase				,		truncation=_UpperCamelCase   )
							UpperCAmelCase_    :      int            =						self.image_processor(images=_UpperCamelCase				,		return_tensors=self.framework   )
							model_inputs.update(_UpperCamelCase   )
							return model_inputs



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase   )	->							Optional[int]:
							UpperCAmelCase_    :      Any            =						self.model(**_UpperCamelCase   )
							return model_outputs



		def 					__UpperCAmelCase			(							self				,		_UpperCamelCase				,		_UpperCamelCase=5   )	->							str:
							if top_k > self.model.config.num_labels:
												UpperCAmelCase_    :      Union[str, Any]            =						self.model.config.num_labels

							if self.framework == "pt":
												UpperCAmelCase_    :      List[str]            =						model_outputs.logits.sigmoid()[0]
												UpperCAmelCase_       ,  UpperCAmelCase_    :      str            =						probs.topk(_UpperCamelCase   )
							else:
												raise ValueError(f"Unsupported framework: {self.framework}"   )

							UpperCAmelCase_    :      Optional[Any]            =						scores.tolist()
							UpperCAmelCase_    :      Tuple            =						ids.tolist()
							return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(_UpperCamelCase				,		_UpperCamelCase   )]






