






import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
		from PIL import Image
else:





		class __lowerCamelCase				:





			"""simple docstring"""






			@staticmethod
			def  UpperCamelCase					(							*UpperCAmelCase ,					**UpperCAmelCase					):
									"""simple docstring"""







									pass





@is_pipeline_test
@require_torch_or_tf
@require_vision
class __lowerCamelCase				(   unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__			=   MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
	UpperCamelCase__			=   TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    ImageClassificationPipeline(model=UpperCAmelCase ,					image_processor=UpperCAmelCase ,					top_k=2					)
							_UpperCAmelCase             =    [
							    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					),
							    'http://images.cocodataset.org/val2017/000000039769.jpg',
							]
							return image_classifier, examples

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase					):
							"""simple docstring"""







							_UpperCAmelCase             =    image_classifier('./tests/fixtures/tests_samples/COCO/000000039769.png'					)

							self.assertEqual(
							    UpperCAmelCase ,					[
							        {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							        {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							    ] ,					)

							import datasets

							_UpperCAmelCase             =    datasets.load_dataset('hf-internal-testing/fixtures_image_utils' ,					'image' ,					split='test'					)

							# Accepts URL + PIL.Image + lists
							_UpperCAmelCase             =    image_classifier(
							    [
							        Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					),
							        'http://images.cocodataset.org/val2017/000000039769.jpg',
							        # RGBA
							        dataset[0]['file'],
							        # LA
							        dataset[1]['file'],
							        # L
							        dataset[2]['file'],
							    ]					)
							self.assertEqual(
							    UpperCAmelCase ,					[
							        [
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							        ],
							        [
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							        ],
							        [
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							        ],
							        [
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							        ],
							        [
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							            {'score': ANY(UpperCAmelCase					), 'label': ANY(UpperCAmelCase					)},
							        ],
							    ] ,					)

	@require_torch
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    'hf-internal-testing/tiny-random-vit'
							_UpperCAmelCase             =    pipeline('image-classification' ,					model=UpperCAmelCase					)

							_UpperCAmelCase             =    image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[{'label': 'LABEL_1', 'score': 0.5_74}, {'label': 'LABEL_0', 'score': 0.4_26}] ,					)

							_UpperCAmelCase             =    image_classifier(
							    [
							        'http://images.cocodataset.org/val2017/000000039769.jpg',
							        'http://images.cocodataset.org/val2017/000000039769.jpg',
							    ] ,					top_k=2 ,					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[
							        [{'label': 'LABEL_1', 'score': 0.5_74}, {'label': 'LABEL_0', 'score': 0.4_26}],
							        [{'label': 'LABEL_1', 'score': 0.5_74}, {'label': 'LABEL_0', 'score': 0.4_26}],
							    ] ,					)

	@require_tf
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    'hf-internal-testing/tiny-random-vit'
							_UpperCAmelCase             =    pipeline('image-classification' ,					model=UpperCAmelCase ,					framework='tf'					)

							_UpperCAmelCase             =    image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[{'label': 'LABEL_1', 'score': 0.5_74}, {'label': 'LABEL_0', 'score': 0.4_26}] ,					)

							_UpperCAmelCase             =    image_classifier(
							    [
							        'http://images.cocodataset.org/val2017/000000039769.jpg',
							        'http://images.cocodataset.org/val2017/000000039769.jpg',
							    ] ,					top_k=2 ,					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[
							        [{'label': 'LABEL_1', 'score': 0.5_74}, {'label': 'LABEL_0', 'score': 0.4_26}],
							        [{'label': 'LABEL_1', 'score': 0.5_74}, {'label': 'LABEL_0', 'score': 0.4_26}],
							    ] ,					)

	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    PreTrainedTokenizer()

							# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
							_UpperCAmelCase             =    pipeline(
							    'image-classification' ,					model='hf-internal-testing/tiny-random-vit' ,					tokenizer=UpperCAmelCase					)

							self.assertIs(image_classifier.tokenizer ,					UpperCAmelCase					)

	@slow
	@require_torch
	def  UpperCamelCase					(							self					):
							"""simple docstring"""







							_UpperCAmelCase             =    pipeline('image-classification' ,					model='deepmind/vision-perceiver-conv'					)
							_UpperCAmelCase             =    image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[
							        {'score': 0.43_85, 'label': 'tabby, tabby cat'},
							        {'score': 0.3_21, 'label': 'tiger cat'},
							        {'score': 0.05_02, 'label': 'Egyptian cat'},
							        {'score': 0.01_37, 'label': 'crib, cot'},
							        {'score': 0.0_07, 'label': 'radiator'},
							    ] ,					)

							_UpperCAmelCase             =    pipeline('image-classification' ,					model='deepmind/vision-perceiver-fourier'					)
							_UpperCAmelCase             =    image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[
							        {'score': 0.56_58, 'label': 'tabby, tabby cat'},
							        {'score': 0.13_09, 'label': 'tiger cat'},
							        {'score': 0.07_22, 'label': 'Egyptian cat'},
							        {'score': 0.07_07, 'label': 'remote control, remote'},
							        {'score': 0.00_82, 'label': 'computer keyboard, keypad'},
							    ] ,					)

							_UpperCAmelCase             =    pipeline('image-classification' ,					model='deepmind/vision-perceiver-learned'					)
							_UpperCAmelCase             =    image_classifier('http://images.cocodataset.org/val2017/000000039769.jpg'					)
							self.assertEqual(
							    nested_simplify(UpperCAmelCase ,					decimals=4					) ,					[
							        {'score': 0.30_22, 'label': 'tabby, tabby cat'},
							        {'score': 0.23_62, 'label': 'Egyptian cat'},
							        {'score': 0.18_56, 'label': 'tiger cat'},
							        {'score': 0.03_24, 'label': 'remote control, remote'},
							        {'score': 0.00_96, 'label': 'quilt, comforter, comfort, puff'},
							    ] ,					)








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,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


_a   			=						logging.get_logger(__name__)


if is_vision_available():
		import PIL





class __lowerCamelCase				(   snake_case__):





	"""simple docstring"""






	UpperCamelCase__			=   ["pixel_values"]

	def __init__(							self ,					UpperCAmelCase = True ,					UpperCAmelCase = None ,					UpperCAmelCase = PILImageResampling.BICUBIC ,					UpperCAmelCase = True ,					UpperCAmelCase = None ,					UpperCAmelCase = True ,					UpperCAmelCase = 1 / 255 ,					UpperCAmelCase = True ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = True ,					**UpperCAmelCase ,					):
							"""simple docstring"""







							super().__init__(**UpperCAmelCase					)
							_UpperCAmelCase             =    size if size is not None else {'shortest_edge': 224}
							_UpperCAmelCase             =    get_size_dict(UpperCAmelCase ,					default_to_square=UpperCAmelCase					)
							_UpperCAmelCase             =    crop_size if crop_size is not None else {'height': 224, 'width': 224}
							_UpperCAmelCase             =    get_size_dict(UpperCAmelCase					)

							_UpperCAmelCase             =    do_resize
							_UpperCAmelCase             =    size
							_UpperCAmelCase             =    resample
							_UpperCAmelCase             =    do_center_crop
							_UpperCAmelCase             =    crop_size
							_UpperCAmelCase             =    do_rescale
							_UpperCAmelCase             =    rescale_factor
							_UpperCAmelCase             =    do_normalize
							_UpperCAmelCase             =    image_mean if image_mean is not None else OPENAI_CLIP_MEAN
							_UpperCAmelCase             =    image_std if image_std is not None else OPENAI_CLIP_STD
							_UpperCAmelCase             =    do_convert_rgb

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase = PILImageResampling.BICUBIC ,					UpperCAmelCase = None ,					**UpperCAmelCase ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    get_size_dict(UpperCAmelCase ,					default_to_square=UpperCAmelCase					)
							_UpperCAmelCase             =    get_resize_output_image_size(
							    UpperCAmelCase ,					size=(size['height'], size['width']) ,					default_to_square=UpperCAmelCase					)
							return resize(UpperCAmelCase ,					size=UpperCAmelCase ,					resample=UpperCAmelCase ,					data_format=UpperCAmelCase ,					**UpperCAmelCase					)

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase = None ,					**UpperCAmelCase ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    get_size_dict(UpperCAmelCase					)
							return center_crop(UpperCAmelCase ,					size=(size['height'], size['width']) ,					data_format=UpperCAmelCase ,					**UpperCAmelCase					)

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase = None ,					**UpperCAmelCase ,					):
							"""simple docstring"""







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

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase ,					UpperCAmelCase = None ,					**UpperCAmelCase ,					):
							"""simple docstring"""







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

	def  UpperCamelCase					(							self ,					UpperCAmelCase ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = None ,					UpperCAmelCase = ChannelDimension.FIRST ,					**UpperCAmelCase ,					):
							"""simple docstring"""







							_UpperCAmelCase             =    do_resize if do_resize is not None else self.do_resize
							_UpperCAmelCase             =    size if size is not None else self.size
							_UpperCAmelCase             =    get_size_dict(UpperCAmelCase ,					default_to_square=UpperCAmelCase					)
							_UpperCAmelCase             =    resample if resample is not None else self.resample
							_UpperCAmelCase             =    do_center_crop if do_center_crop is not None else self.do_center_crop
							_UpperCAmelCase             =    crop_size if crop_size is not None else self.crop_size
							_UpperCAmelCase             =    get_size_dict(UpperCAmelCase					)
							_UpperCAmelCase             =    do_rescale if do_rescale is not None else self.do_rescale
							_UpperCAmelCase             =    rescale_factor if rescale_factor is not None else self.rescale_factor
							_UpperCAmelCase             =    do_normalize if do_normalize is not None else self.do_normalize
							_UpperCAmelCase             =    image_mean if image_mean is not None else self.image_mean
							_UpperCAmelCase             =    image_std if image_std is not None else self.image_std
							_UpperCAmelCase             =    do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

							_UpperCAmelCase             =    make_list_of_images(UpperCAmelCase					)

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

							# PIL RGBA images are converted to RGB
							if do_convert_rgb:
													_UpperCAmelCase             =    [convert_to_rgb(UpperCAmelCase					) for image in images]

							# All transformations expect numpy arrays.
							_UpperCAmelCase             =    [to_numpy_array(UpperCAmelCase					) for image in images]

							if do_resize:
													_UpperCAmelCase             =    [self.resize(image=UpperCAmelCase ,					size=UpperCAmelCase ,					resample=UpperCAmelCase					) for image in images]

							if do_center_crop:
													_UpperCAmelCase             =    [self.center_crop(image=UpperCAmelCase ,					size=UpperCAmelCase					) for image in images]

							if do_rescale:
													_UpperCAmelCase             =    [self.rescale(image=UpperCAmelCase ,					scale=UpperCAmelCase					) for image in images]

							if do_normalize:
													_UpperCAmelCase             =    [self.normalize(image=UpperCAmelCase ,					mean=UpperCAmelCase ,					std=UpperCAmelCase					) for image in images]

							_UpperCAmelCase             =    [to_channel_dimension_format(UpperCAmelCase ,					UpperCAmelCase					) for image in images]

							_UpperCAmelCase             =    {'pixel_values': images}
							return BatchFeature(data=UpperCAmelCase ,					tensor_type=UpperCAmelCase					)
