




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 		__UpperCAmelCase:





      """simple docstring"""



      @staticmethod
      def 				__SCREAMING_SNAKE_CASE		(      *A :       str						,				**A :       int    )			->			Union[str, Any]:






          """simple docstring"""
          pass







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





     """simple docstring"""



     __UpperCAmelCase	: Tuple						=    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
     __UpperCAmelCase	: Dict						=    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

     def 				__SCREAMING_SNAKE_CASE		(      self :       str						,				A :       Optional[int]						,				A :       Tuple						,				A :       int    )			->			str:






         """simple docstring"""
         a__      =       ImageClassificationPipeline(model=A						,				image_processor=A						,				top_k=2    )
         a__      =       [
             Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    ),
             """http://images.cocodataset.org/val2017/000000039769.jpg""",
         ]
         return image_classifier, examples

     def 				__SCREAMING_SNAKE_CASE		(      self :       Any						,				A :       List[str]						,				A :       Dict    )			->			Union[str, Any]:






         """simple docstring"""
         a__      =       image_classifier("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )

         self.assertEqual(
             A						,				[
                 {"""score""": ANY(A    ), """label""": ANY(A    )},
                 {"""score""": ANY(A    ), """label""": ANY(A    )},
             ]						,				)

         import datasets

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

         # Accepts URL + PIL.Image + lists
         a__      =       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(
             A						,				[
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
                 [
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                     {"""score""": ANY(A    ), """label""": ANY(A    )},
                 ],
             ]						,				)

     @require_torch
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]    )			->			Optional[Any]:






         """simple docstring"""
         a__      =       """hf-internal-testing/tiny-random-vit"""
         a__      =       pipeline("""image-classification"""						,				model=A    )

         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]						,				)

         a__      =       image_classifier(
             [
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
             ]						,				top_k=2						,				)
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
             ]						,				)

     @require_tf
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			str:






         """simple docstring"""
         a__      =       """hf-internal-testing/tiny-random-vit"""
         a__      =       pipeline("""image-classification"""						,				model=A						,				framework="""tf"""    )

         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}]						,				)

         a__      =       image_classifier(
             [
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
                 """http://images.cocodataset.org/val2017/000000039769.jpg""",
             ]						,				top_k=2						,				)
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
                 [{"""label""": """LABEL_1""", """score""": 0.5_7_4}, {"""label""": """LABEL_0""", """score""": 0.4_2_6}],
             ]						,				)

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]    )			->			str:






         """simple docstring"""
         a__      =       PreTrainedTokenizer()

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

         self.assertIs(image_classifier.tokenizer						,				A    )






     @slow
     @require_torch
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			Dict:






         """simple docstring"""
         # Perceiver is not tested by `run_pipeline_test` properly.
         # That is because the type of feature_extractor and model preprocessor need to be kept
         # in sync, which is not the case in the current design
         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-conv"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.4_3_8_5, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.3_2_1, """label""": """tiger cat"""},
                 {"""score""": 0.0_5_0_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.0_1_3_7, """label""": """crib, cot"""},
                 {"""score""": 0.0_0_7, """label""": """radiator"""},
             ]						,				)

         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-fourier"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.5_6_5_8, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.1_3_0_9, """label""": """tiger cat"""},
                 {"""score""": 0.0_7_2_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.0_7_0_7, """label""": """remote control, remote"""},
                 {"""score""": 0.0_0_8_2, """label""": """computer keyboard, keypad"""},
             ]						,				)

         a__      =       pipeline("""image-classification"""						,				model="""deepmind/vision-perceiver-learned"""    )
         a__      =       image_classifier("""http://images.cocodataset.org/val2017/000000039769.jpg"""    )
         self.assertEqual(
             nested_simplify(A						,				decimals=4    )						,				[
                 {"""score""": 0.3_0_2_2, """label""": """tabby, tabby cat"""},
                 {"""score""": 0.2_3_6_2, """label""": """Egyptian cat"""},
                 {"""score""": 0.1_8_5_6, """label""": """tiger cat"""},
                 {"""score""": 0.0_3_2_4, """label""": """remote control, remote"""},
                 {"""score""": 0.0_0_9_6, """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, 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, is_vision_available, logging


if is_vision_available():
 import PIL


SCREAMING_SNAKE_CASE_						:					Any			   =       logging.get_logger(__name__)







class 		__UpperCAmelCase(		lowercase__ ):





     """simple docstring"""



     __UpperCAmelCase	: Optional[Any]						=    ["""pixel_values"""]

     def __init__(      self :       int						,				A :       bool = True						,				A :       Dict[str, int] = None						,				A :       PILImageResampling = PIL.Image.NEAREST						,				A :       bool = False						,				A :       Dict[str, int] = None						,				A :       Union[int, float] = 1 / 2_55						,				A :       bool = False						,				A :       bool = True						,				A :       bool = True						,				A :       Optional[Union[float, List[float]]] = None						,				A :       Optional[Union[float, List[float]]] = None						,				A :       bool = True						,				**A :       Optional[int]						,				)			->			None:






         """simple docstring"""
         super().__init__(**A    )
         a__      =       size if size is not None else {"""height""": 3_46, """width""": 3_46}
         a__      =       get_size_dict(A    )
         a__      =       crop_size if crop_size is not None else {"""height""": 2_89, """width""": 2_89}
         a__      =       get_size_dict(A						,				param_name="""crop_size"""    )

         a__      =       do_resize
         a__      =       size
         a__      =       resample
         a__      =       do_center_crop
         a__      =       crop_size
         a__      =       do_rescale
         a__      =       rescale_factor
         a__      =       rescale_offset
         a__      =       do_normalize
         a__      =       image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         a__      =       image_std if image_std is not None else IMAGENET_STANDARD_STD
         a__      =       include_top

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]						,				A :       np.ndarray						,				A :       Dict[str, int]						,				A :       PILImageResampling = PIL.Image.NEAREST						,				A :       Optional[Union[str, ChannelDimension]] = None						,				**A :       Dict						,				)			->			np.ndarray:






         """simple docstring"""
         a__      =       get_size_dict(A    )
         if "height" not in size or "width" not in size:
             raise ValueError(f"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"""    )
         return resize(
             A						,				size=(size["""height"""], size["""width"""])						,				resample=A						,				data_format=A						,				**A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple						,				A :       np.ndarray						,				A :       Dict[str, int]						,				A :       Optional[Union[str, ChannelDimension]] = None						,				**A :       Optional[Any]						,				)			->			np.ndarray:






         """simple docstring"""
         a__      =       get_size_dict(A    )
         if "height" not in size or "width" not in size:
             raise ValueError(f"""The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"""    )
         return center_crop(A						,				size=(size["""height"""], size["""width"""])						,				data_format=A						,				**A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict						,				A :       np.ndarray						,				A :       Union[int, float]						,				A :       bool = True						,				A :       Optional[Union[str, ChannelDimension]] = None						,				**A :       List[str]						,				)			->			Any:






         """simple docstring"""
         if offset:
             a__      =       (image - 1_2_7.5) * scale
             if data_format is not None:
                 a__      =       to_channel_dimension_format(A						,				A    )
             a__      =       rescaled_image.astype(np.floataa    )
         else:
             a__      =       rescale(A						,				scale=A						,				data_format=A						,				**A    )
         return rescaled_image

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]						,				A :       np.ndarray						,				A :       Union[float, List[float]]						,				A :       Union[float, List[float]]						,				A :       Optional[Union[str, ChannelDimension]] = None						,				**A :       str						,				)			->			np.ndarray:






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






     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]						,				A :       ImageInput						,				A :       bool = None						,				A :       Dict[str, int] = None						,				A :       Any=None						,				A :       bool = None						,				A :       Dict[str, int] = None						,				A :       bool = None						,				A :       float = None						,				A :       bool = None						,				A :       bool = None						,				A :       Optional[Union[float, List[float]]] = None						,				A :       Optional[Union[float, List[float]]] = None						,				A :       bool = None						,				A :       Optional[Union[str, TensorType]] = None						,				A :       ChannelDimension = ChannelDimension.FIRST						,				**A :       Tuple						,				)			->			PIL.Image.Image:






         """simple docstring"""
         a__      =       do_resize if do_resize is not None else self.do_resize
         a__      =       resample if resample is not None else self.resample
         a__      =       do_center_crop if do_center_crop is not None else self.do_center_crop
         a__      =       do_rescale if do_rescale is not None else self.do_rescale
         a__      =       rescale_factor if rescale_factor is not None else self.rescale_factor
         a__      =       rescale_offset if rescale_offset is not None else self.rescale_offset
         a__      =       do_normalize if do_normalize is not None else self.do_normalize
         a__      =       image_mean if image_mean is not None else self.image_mean
         a__      =       image_std if image_std is not None else self.image_std
         a__      =       include_top if include_top is not None else self.include_top

         a__      =       size if size is not None else self.size
         a__      =       get_size_dict(A    )
         a__      =       crop_size if crop_size is not None else self.crop_size
         a__      =       get_size_dict(A						,				param_name="""crop_size"""    )

         a__      =       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 or resample is None:
             raise ValueError("""Size and resample 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.
         a__      =       [to_numpy_array(A    ) for image in images]

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

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

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

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

         if include_top:
             a__      =       [self.normalize(image=A						,				mean=[0, 0, 0]						,				std=A    ) for image in images]

         a__      =       [to_channel_dimension_format(A						,				A    ) for image in images]

         a__      =       {"""pixel_values""": images}
         return BatchFeature(data=A						,				tensor_type=A    )






