



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 						lowercase    :
									'''simple docstring'''


									@staticmethod
									def       lowerCamelCase_				(  *snake_case    :				Dict       ,	**snake_case    :				List[Any]	):



														'''simple docstring'''


														pass


@is_pipeline_test
@require_torch
@require_vision
class 						lowercase    (							unittest.TestCase):
						'''simple docstring'''


						UpperCAmelCase			:		Any		=		MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING







						def       lowerCamelCase_				(  self    :				List[Any]       ,	snake_case    :				List[str]       ,	snake_case    :				int       ,	snake_case    :				Optional[Any]	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				pipeline('visual-question-answering'       ,	model='hf-internal-testing/tiny-vilt-random-vqa'	)
											SCREAMING_SNAKE_CASE							:     Any						=				[
											    {
											        '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    :				int       ,	snake_case    :				int       ,	snake_case    :				Dict	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				vqa_pipeline(snake_case       ,	top_k=1	)
											self.assertEqual(
											    snake_case       ,	[
											        [{'score': ANY(snake_case	), 'answer': ANY(snake_case	)}],
											        [{'score': ANY(snake_case	), 'answer': ANY(snake_case	)}],
											    ]       ,	)







						@require_torch
						def       lowerCamelCase_				(  self    :				Dict	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				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							:     Any						=				'How many cats are there?'

											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				vqa_pipeline(image=snake_case       ,	question='How many cats are there?'       ,	top_k=2	)
											self.assertEqual(
											    snake_case       ,	[{'score': ANY(snake_case	), 'answer': ANY(snake_case	)}, {'score': ANY(snake_case	), 'answer': ANY(snake_case	)}]	)

											SCREAMING_SNAKE_CASE							:     int						=				vqa_pipeline({'image': image, 'question': question}       ,	top_k=2	)
											self.assertEqual(
											    snake_case       ,	[{'score': ANY(snake_case	), 'answer': ANY(snake_case	)}, {'score': ANY(snake_case	), 'answer': ANY(snake_case	)}]	)







						@slow
						@require_torch
						def       lowerCamelCase_				(  self    :				Dict	):



											'''simple docstring'''


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

											SCREAMING_SNAKE_CASE							:     int						=				vqa_pipeline(image=snake_case       ,	question=snake_case       ,	top_k=2	)
											self.assertEqual(
											    nested_simplify(snake_case       ,	decimals=4	)       ,	[{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]	)

											SCREAMING_SNAKE_CASE							:     List[str]						=				vqa_pipeline({'image': image, 'question': question}       ,	top_k=2	)
											self.assertEqual(
											    nested_simplify(snake_case       ,	decimals=4	)       ,	[{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]	)

											SCREAMING_SNAKE_CASE							:     Any						=				vqa_pipeline(
											    [{'image': image, 'question': question}, {'image': image, 'question': question}]       ,	top_k=2	)
											self.assertEqual(
											    nested_simplify(snake_case       ,	decimals=4	)       ,	[[{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2       ,	)







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



											'''simple docstring'''


											pass




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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    is_batched,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCamelCase    :		List[str]		      =    logging.get_logger(__name__)


class 						lowercase    (							SCREAMING_SNAKE_CASE_):
						'''simple docstring'''


						UpperCAmelCase			:		List[str]		=		['pixel_values']







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



											'''simple docstring'''


											super().__init__(**snake_case	)
											SCREAMING_SNAKE_CASE							:     List[str]						=				size if size is not None else {'height': 224, 'width': 224}
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				get_size_dict(snake_case	)
											SCREAMING_SNAKE_CASE							:     Any						=				crop_size if crop_size is not None else {'height': 224, 'width': 224}
											SCREAMING_SNAKE_CASE							:     int						=				get_size_dict(snake_case       ,	default_to_square=snake_case       ,	param_name='crop_size'	)

											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				do_resize
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				do_rescale
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				do_normalize
											SCREAMING_SNAKE_CASE							:     Dict						=				do_center_crop
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				crop_size
											SCREAMING_SNAKE_CASE							:     str						=				size
											SCREAMING_SNAKE_CASE							:     List[str]						=				resample
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				rescale_factor
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
											SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				image_std if image_std is not None else IMAGENET_DEFAULT_STD







						def       lowerCamelCase_				(  self    :				int       ,	snake_case    :				np.ndarray       ,	snake_case    :				Dict[str, int]       ,	snake_case    :				PILImageResampling = PILImageResampling.BILINEAR       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				Any       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     List[Any]						=				get_size_dict(snake_case	)

											if "shortest_edge" in size:
																SCREAMING_SNAKE_CASE							:     Tuple						=				get_resize_output_image_size(snake_case       ,	size=size['shortest_edge']       ,	default_to_square=snake_case	)
																# size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
											elif "height" in size and "width" in size:
																SCREAMING_SNAKE_CASE							:     int						=				(size['height'], size['width'])
											else:
																raise ValueError(f'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}'''	)
											return resize(snake_case       ,	size=snake_case       ,	resample=snake_case       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				List[str]       ,	snake_case    :				np.ndarray       ,	snake_case    :				Dict[str, int]       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				int       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Tuple						=				get_size_dict(snake_case	)
											if "height" not in size or "width" not in size:
																raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}'''	)
											return center_crop(snake_case       ,	size=(size['height'], size['width'])       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				Any       ,	snake_case    :				np.ndarray       ,	snake_case    :				float       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				Dict	):



											'''simple docstring'''


											return rescale(snake_case       ,	scale=snake_case       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				List[Any]       ,	snake_case    :				np.ndarray       ,	snake_case    :				Union[float, List[float]]       ,	snake_case    :				Union[float, List[float]]       ,	snake_case    :				Optional[Union[str, ChannelDimension]] = None       ,	**snake_case    :				List[Any]       ,	):



											'''simple docstring'''


											return normalize(snake_case       ,	mean=snake_case       ,	std=snake_case       ,	data_format=snake_case       ,	**snake_case	)







						def       lowerCamelCase_				(  self    :				str       ,	snake_case    :				ImageInput       ,	snake_case    :				Optional[bool] = None       ,	snake_case    :				Dict[str, int] = None       ,	snake_case    :				PILImageResampling = None       ,	snake_case    :				bool = None       ,	snake_case    :				int = None       ,	snake_case    :				Optional[bool] = None       ,	snake_case    :				Optional[float] = None       ,	snake_case    :				Optional[bool] = None       ,	snake_case    :				Optional[Union[float, List[float]]] = None       ,	snake_case    :				Optional[Union[float, List[float]]] = None       ,	snake_case    :				Optional[Union[str, TensorType]] = None       ,	snake_case    :				Union[str, ChannelDimension] = ChannelDimension.FIRST       ,	**snake_case    :				Optional[Any]       ,	):



											'''simple docstring'''


											SCREAMING_SNAKE_CASE							:     Any						=				do_resize if do_resize is not None else self.do_resize
											SCREAMING_SNAKE_CASE							:     int						=				do_rescale if do_rescale is not None else self.do_rescale
											SCREAMING_SNAKE_CASE							:     Optional[int]						=				do_normalize if do_normalize is not None else self.do_normalize
											SCREAMING_SNAKE_CASE							:     List[str]						=				do_center_crop if do_center_crop is not None else self.do_center_crop
											SCREAMING_SNAKE_CASE							:     List[str]						=				crop_size if crop_size is not None else self.crop_size
											SCREAMING_SNAKE_CASE							:     List[Any]						=				get_size_dict(snake_case       ,	param_name='crop_size'       ,	default_to_square=snake_case	)
											SCREAMING_SNAKE_CASE							:     Any						=				resample if resample is not None else self.resample
											SCREAMING_SNAKE_CASE							:     Any						=				rescale_factor if rescale_factor is not None else self.rescale_factor
											SCREAMING_SNAKE_CASE							:     str						=				image_mean if image_mean is not None else self.image_mean
											SCREAMING_SNAKE_CASE							:     Optional[Any]						=				image_std if image_std is not None else self.image_std

											SCREAMING_SNAKE_CASE							:     List[str]						=				size if size is not None else self.size
											SCREAMING_SNAKE_CASE							:     str						=				get_size_dict(snake_case	)

											if not is_batched(snake_case	):
																SCREAMING_SNAKE_CASE							:     str						=				[images]

											if not valid_images(snake_case	):
																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.'	)

											# All transformations expect numpy arrays.
											SCREAMING_SNAKE_CASE							:     Dict						=				[to_numpy_array(snake_case	) for image in images]

											if do_resize:
																SCREAMING_SNAKE_CASE							:     Union[str, Any]						=				[self.resize(image=snake_case       ,	size=snake_case       ,	resample=snake_case	) for image in images]

											if do_center_crop:
																SCREAMING_SNAKE_CASE							:     str						=				[self.center_crop(image=snake_case       ,	size=snake_case	) for image in images]

											if do_rescale:
																SCREAMING_SNAKE_CASE							:     Tuple						=				[self.rescale(image=snake_case       ,	scale=snake_case	) for image in images]

											if do_normalize:
																SCREAMING_SNAKE_CASE							:     int						=				[self.normalize(image=snake_case       ,	mean=snake_case       ,	std=snake_case	) for image in images]

											SCREAMING_SNAKE_CASE							:     List[str]						=				[to_channel_dimension_format(snake_case       ,	snake_case	) for image in images]

											SCREAMING_SNAKE_CASE							:     Any						=				{'pixel_values': images}
											return BatchFeature(data=snake_case       ,	tensor_type=snake_case	)