

"""simple docstring"""




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


__UpperCAmelCase =				logging.get_logger(__name__)







class      __lowercase			(    __lowerCamelCase					):
		snake_case_				       =       ["""pixel_values"""]

		def __init__(  self		:			Optional[int]					,A		:			int = True					,A		:			Union[str, Any] = None					,A		:			Dict = PILImageResampling.BILINEAR					,A		:			Optional[int] = True					,A		:			Union[str, Any] = None					,A		:			Optional[int] = True					,A		:			str = 1 / 255					,A		:			List[str] = True					,A		:			List[str] = None					,A		:			Optional[int] = None					,**A		:			Dict					,):






			'''simple docstring'''
			super().__init__(**A    )
			UpperCAmelCase__					:  Tuple					   =					size if size is not None else {"""shortest_edge""": 256}
			UpperCAmelCase__					:  Union[str, Any]					   =					get_size_dict(A					,default_to_square=A    )
			UpperCAmelCase__					:  Tuple					   =					crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
			UpperCAmelCase__					:  Union[str, Any]					   =					get_size_dict(A    )
			UpperCAmelCase__					:  List[Any]					   =					do_resize
			UpperCAmelCase__					:  Optional[int]					   =					size
			UpperCAmelCase__					:  List[str]					   =					resample
			UpperCAmelCase__					:  int					   =					do_center_crop
			UpperCAmelCase__					:  Optional[int]					   =					crop_size
			UpperCAmelCase__					:  List[Any]					   =					do_rescale
			UpperCAmelCase__					:  str					   =					rescale_factor
			UpperCAmelCase__					:  Any					   =					do_normalize
			UpperCAmelCase__					:  Tuple					   =					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
			UpperCAmelCase__					:  int					   =					image_std if image_std is not None else IMAGENET_STANDARD_STD

		def    __lowercase       (  self		:			int					,A		:			int					,A		:			Optional[Any]					,A		:			Union[str, Any] = PILImageResampling.BICUBIC					,A		:			Optional[int] = None					,**A		:			List[str]					,):






			'''simple docstring'''
			UpperCAmelCase__					:  Optional[Any]					   =					get_size_dict(A					,default_to_square=A    )
			if "shortest_edge" not in size:
				raise ValueError(f"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"    )
			UpperCAmelCase__					:  int					   =					get_resize_output_image_size(A					,size=size["""shortest_edge"""]					,default_to_square=A    )
			return resize(A					,size=A					,resample=A					,data_format=A					,**A    )

		def    __lowercase       (  self		:			Any					,A		:			Optional[Any]					,A		:			Tuple					,A		:			List[str] = None					,**A		:			Any					,):






			'''simple docstring'''
			UpperCAmelCase__					:  Tuple					   =					get_size_dict(A    )
			return center_crop(A					,size=(size["""height"""], size["""width"""])					,data_format=A					,**A    )

		def    __lowercase       (  self		:			str					,A		:			List[str]					,A		:			int					,A		:			Tuple = None					,**A		:			int    ):






			'''simple docstring'''
			return rescale(A					,scale=A					,data_format=A					,**A    )

		def    __lowercase       (  self		:			Optional[int]					,A		:			Tuple					,A		:			List[Any]					,A		:			List[Any]					,A		:			str = None					,**A		:			Tuple					,):






			'''simple docstring'''
			return normalize(A					,mean=A					,std=A					,data_format=A					,**A    )




		def    __lowercase       (  self		:			List[str]					,A		:			Tuple					,A		:			Optional[int] = None					,A		:			Any = None					,A		:			Optional[Any] = None					,A		:			List[str] = None					,A		:			Union[str, Any] = None					,A		:			int = None					,A		:			List[str] = None					,A		:			Tuple = None					,A		:			Any = None					,A		:			Optional[int] = None					,A		:			Any = None					,A		:			Tuple = ChannelDimension.FIRST					,**A		:			Dict					,):






			'''simple docstring'''
			UpperCAmelCase__					:  Tuple					   =					do_resize if do_resize is not None else self.do_resize
			UpperCAmelCase__					:  Optional[int]					   =					size if size is not None else self.size
			UpperCAmelCase__					:  Dict					   =					get_size_dict(A					,default_to_square=A    )
			UpperCAmelCase__					:  Dict					   =					resample if resample is not None else self.resample
			UpperCAmelCase__					:  List[Any]					   =					do_center_crop if do_center_crop is not None else self.do_center_crop
			UpperCAmelCase__					:  List[Any]					   =					crop_size if crop_size is not None else self.crop_size
			UpperCAmelCase__					:  int					   =					get_size_dict(A    )
			UpperCAmelCase__					:  str					   =					do_rescale if do_rescale is not None else self.do_rescale
			UpperCAmelCase__					:  Any					   =					rescale_factor if rescale_factor is not None else self.rescale_factor
			UpperCAmelCase__					:  Union[str, Any]					   =					do_normalize if do_normalize is not None else self.do_normalize
			UpperCAmelCase__					:  Dict					   =					image_mean if image_mean is not None else self.image_mean
			UpperCAmelCase__					:  Optional[int]					   =					image_std if image_std is not None else self.image_std

			UpperCAmelCase__					:  Any					   =					make_list_of_images(A    )

			if not valid_images(A    ):
				raise ValueError(
				    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
				    """torch.Tensor, tf.Tensor or jax.ndarray."""    )

			if do_resize and size is None:
				raise ValueError("""Size must be specified if do_resize is True."""    )

			if do_center_crop and crop_size is None:
				raise ValueError("""Crop size must be specified if do_center_crop is True."""    )

			if do_rescale and rescale_factor is None:
				raise ValueError("""Rescale factor must be specified if do_rescale is True."""    )

			if do_normalize and (image_mean is None or image_std is None):
				raise ValueError("""Image mean and std must be specified if do_normalize is True."""    )

			# All transformations expect numpy arrays.
			UpperCAmelCase__					:  Tuple					   =					[to_numpy_array(A    ) for image in images]

			if do_resize:
				UpperCAmelCase__					:  Tuple					   =					[self.resize(image=A					,size=A					,resample=A    ) for image in images]

			if do_center_crop:
				UpperCAmelCase__					:  Tuple					   =					[self.center_crop(image=A					,size=A    ) for image in images]

			if do_rescale:
				UpperCAmelCase__					:  Any					   =					[self.rescale(image=A					,scale=A    ) for image in images]

			if do_normalize:
				UpperCAmelCase__					:  Union[str, Any]					   =					[self.normalize(image=A					,mean=A					,std=A    ) for image in images]

			UpperCAmelCase__					:  str					   =					[to_channel_dimension_format(A					,A    ) for image in images]

			UpperCAmelCase__					:  Union[str, Any]					   =					{"""pixel_values""": images}
			return BatchFeature(data=A					,tensor_type=A    )








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

__UpperCAmelCase =				logging.get_logger(__name__)







@add_end_docstrings(__lowerCamelCase					)
class      __lowercase			(    __lowerCamelCase					):

  def __init__(  self		:			List[str]					,*A		:			Optional[int]					,**A		:			List[str]    ):






   '''simple docstring'''
   super().__init__(*A					,**A    )
   self.check_model_type(A    )

  def    __lowercase       (  self		:			Optional[int]					,A		:			Dict=None					,A		:			Optional[int]=None					,A		:			Tuple=None					,**A		:			str    ):






   '''simple docstring'''
   UpperCAmelCase__   ,      UpperCAmelCase__					:  Any					   =					{}, {}
   if padding is not None:
    UpperCAmelCase__					:  Union[str, Any]					   =					padding
   if truncation is not None:
    UpperCAmelCase__					:  List[str]					   =					truncation
   if top_k is not None:
    UpperCAmelCase__					:  List[Any]					   =					top_k
   return preprocess_params, {}, postprocess_params

  def __call__(  self		:			List[Any]					,A		:			Union["Image.Image", str]					,A		:			str = None					,**A		:			Union[str, Any]    ):






   '''simple docstring'''
   if isinstance(A					,(Image.Image, str)    ) and isinstance(A					,A    ):
    UpperCAmelCase__					:  Any					   =					{"""image""": image, """question""": question}
   else:
    UpperCAmelCase__					:  Dict					   =					image
   UpperCAmelCase__					:  Dict					   =					super().__call__(A					,**A    )
   return results

  def    __lowercase       (  self		:			Optional[int]					,A		:			Optional[Any]					,A		:			Optional[Any]=False					,A		:			List[Any]=False    ):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					load_image(inputs["""image"""]    )
   UpperCAmelCase__					:  Optional[Any]					   =					self.tokenizer(
       inputs["""question"""]					,return_tensors=self.framework					,padding=A					,truncation=A    )
   UpperCAmelCase__					:  int					   =					self.image_processor(images=A					,return_tensors=self.framework    )
   model_inputs.update(A    )
   return model_inputs

  def    __lowercase       (  self		:			Dict					,A		:			Tuple    ):






   '''simple docstring'''
   UpperCAmelCase__					:  List[Any]					   =					self.model(**A    )
   return model_outputs




  def    __lowercase       (  self		:			int					,A		:			List[Any]					,A		:			List[str]=5    ):






   '''simple docstring'''
   if top_k > self.model.config.num_labels:
    UpperCAmelCase__					:  Any					   =					self.model.config.num_labels

   if self.framework == "pt":
    UpperCAmelCase__					:  Optional[int]					   =					model_outputs.logits.sigmoid()[0]
    UpperCAmelCase__   ,      UpperCAmelCase__					:  Optional[int]					   =					probs.topk(A    )
   else:
    raise ValueError(f"Unsupported framework: {self.framework}"    )

   UpperCAmelCase__					:  List[str]					   =					scores.tolist()
   UpperCAmelCase__					:  Optional[int]					   =					ids.tolist()
   return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(A					,A    )]





