

import unittest

import numpy as np
from datasets import load_dataset

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
					import torch

if is_vision_available():
					from PIL import Image

					from transformers import SegformerImageProcessor

class  a     (		unittest.TestCase ):


						def __init__(				self  ,    A_  ,    A_=7  ,    A_=3  ,    A_=30  ,    A_=400  ,    A_=True  ,    A_=None  ,    A_=True  ,    A_=[0.5, 0.5, 0.5]  ,    A_=[0.5, 0.5, 0.5]  ,    A_=False  ,    ):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			size if size is not None else {"height": 30, "width": 30}
										_UpperCAmelCase				:						Any       						=			parent
										_UpperCAmelCase				:						Optional[Any]       						=			batch_size
										_UpperCAmelCase				:						str       						=			num_channels
										_UpperCAmelCase				:						Tuple       						=			min_resolution
										_UpperCAmelCase				:						List[Any]       						=			max_resolution
										_UpperCAmelCase				:						Union[str, Any]       						=			do_resize
										_UpperCAmelCase				:						Optional[Any]       						=			size
										_UpperCAmelCase				:						str       						=			do_normalize
										_UpperCAmelCase				:						Any       						=			image_mean
										_UpperCAmelCase				:						Tuple       						=			image_std
										_UpperCAmelCase				:						List[str]       						=			do_reduce_labels





						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										return {
										    "do_resize": self.do_resize,
										    "size": self.size,
										    "do_normalize": self.do_normalize,
										    "image_mean": self.image_mean,
										    "image_std": self.image_std,
										    "do_reduce_labels": self.do_reduce_labels,
										}







def 							__SCREAMING_SNAKE_CASE							( )      ->				List[str]:
				_UpperCAmelCase				:						Tuple       						=			load_dataset("hf-internal-testing/fixtures_ade20k"     ,					split="test"       )

				_UpperCAmelCase				:						List[Any]       						=			Image.open(dataset[0]["file"]       )
				_UpperCAmelCase				:						Optional[int]       						=			Image.open(dataset[1]["file"]       )

				return image, map

def 							__SCREAMING_SNAKE_CASE							( )      ->				List[str]:
				_UpperCAmelCase				:						List[str]       						=			load_dataset("hf-internal-testing/fixtures_ade20k"     ,					split="test"       )

				_UpperCAmelCase				:						str       						=			Image.open(dataset[0]["file"]       )
				_UpperCAmelCase				:						List[Any]       						=			Image.open(dataset[1]["file"]       )
				_UpperCAmelCase				:						Union[str, Any]       						=			Image.open(dataset[2]["file"]       )
				_UpperCAmelCase				:						List[Any]       						=			Image.open(dataset[3]["file"]       )

				return [imagea, imagea], [mapa, mapa]





@require_torch
@require_vision
class  a     (		UpperCAmelCase							,       unittest.TestCase ):
						_lowercase			  =	SegformerImageProcessor if is_vision_available() else None


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			SegformerImageProcessingTester(self		)


						@property
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										return self.image_processor_tester.prepare_image_processor_dict()


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						List[str]       						=			self.image_processing_class(**self.image_processor_dict		)
										self.assertTrue(hasattr(A_  ,    "do_resize"		)		)
										self.assertTrue(hasattr(A_  ,    "size"		)		)
										self.assertTrue(hasattr(A_  ,    "do_normalize"		)		)
										self.assertTrue(hasattr(A_  ,    "image_mean"		)		)
										self.assertTrue(hasattr(A_  ,    "image_std"		)		)
										self.assertTrue(hasattr(A_  ,    "do_reduce_labels"		)		)


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						str       						=			self.image_processing_class.from_dict(self.image_processor_dict		)
										self.assertEqual(image_processor.size  ,    {"height": 30, "width": 30}		)
										self.assertEqual(image_processor.do_reduce_labels  ,    A_		)

										_UpperCAmelCase				:						Dict       						=			self.image_processing_class.from_dict(self.image_processor_dict  ,    size=42  ,    reduce_labels=A_		)
										self.assertEqual(image_processor.size  ,    {"height": 42, "width": 42}		)
										self.assertEqual(image_processor.do_reduce_labels  ,    A_		)


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										pass


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						List[str]       						=			self.image_processing_class(**self.image_processor_dict		)
										# create random PIL images
										_UpperCAmelCase				:						Dict       						=			prepare_image_inputs(self.image_processor_tester  ,    equal_resolution=A_		)
										for image in image_inputs:
														self.assertIsInstance(A_  ,    Image.Image		)

										# Test not batched input
										_UpperCAmelCase				:						List[Any]       						=			image_processing(image_inputs[0]  ,    return_tensors="pt"		).pixel_values
										self.assertEqual(
										    encoded_images.shape  ,    (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )

										# Test batched
										_UpperCAmelCase				:						Union[str, Any]       						=			image_processing(A_  ,    return_tensors="pt"		).pixel_values
										self.assertEqual(
										    encoded_images.shape  ,    (
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						List[str]       						=			self.image_processing_class(**self.image_processor_dict		)
										# create random numpy tensors
										_UpperCAmelCase				:						List[Any]       						=			prepare_image_inputs(self.image_processor_tester  ,    equal_resolution=A_  ,    numpify=A_		)
										for image in image_inputs:
														self.assertIsInstance(A_  ,    np.ndarray		)

										# Test not batched input
										_UpperCAmelCase				:						int       						=			image_processing(image_inputs[0]  ,    return_tensors="pt"		).pixel_values
										self.assertEqual(
										    encoded_images.shape  ,    (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )

										# Test batched
										_UpperCAmelCase				:						Optional[int]       						=			image_processing(A_  ,    return_tensors="pt"		).pixel_values
										self.assertEqual(
										    encoded_images.shape  ,    (
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						str       						=			self.image_processing_class(**self.image_processor_dict		)
										# create random PyTorch tensors
										_UpperCAmelCase				:						Optional[Any]       						=			prepare_image_inputs(self.image_processor_tester  ,    equal_resolution=A_  ,    torchify=A_		)
										for image in image_inputs:
														self.assertIsInstance(A_  ,    torch.Tensor		)

										# Test not batched input
										_UpperCAmelCase				:						Union[str, Any]       						=			image_processing(image_inputs[0]  ,    return_tensors="pt"		).pixel_values
										self.assertEqual(
										    encoded_images.shape  ,    (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )

										# Test batched
										_UpperCAmelCase				:						Dict       						=			image_processing(A_  ,    return_tensors="pt"		).pixel_values
										self.assertEqual(
										    encoded_images.shape  ,    (
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )


						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						List[Any]       						=			self.image_processing_class(**self.image_processor_dict		)
										# create random PyTorch tensors
										_UpperCAmelCase				:						int       						=			prepare_image_inputs(self.image_processor_tester  ,    equal_resolution=A_  ,    torchify=A_		)
										_UpperCAmelCase				:						Dict       						=			[]
										for image in image_inputs:
														self.assertIsInstance(A_  ,    torch.Tensor		)
														maps.append(torch.zeros(image.shape[-2:]		).long()		)

										# Test not batched input
										_UpperCAmelCase				:						Optional[Any]       						=			image_processing(image_inputs[0]  ,    maps[0]  ,    return_tensors="pt"		)
										self.assertEqual(
										    encoding["pixel_values"].shape  ,    (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(
										    encoding["labels"].shape  ,    (
										        1,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(encoding["labels"].dtype  ,    torch.long		)
										self.assertTrue(encoding["labels"].min().item() >= 0		)
										self.assertTrue(encoding["labels"].max().item() <= 255		)

										# Test batched
										_UpperCAmelCase				:						str       						=			image_processing(A_  ,    A_  ,    return_tensors="pt"		)
										self.assertEqual(
										    encoding["pixel_values"].shape  ,    (
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(
										    encoding["labels"].shape  ,    (
										        self.image_processor_tester.batch_size,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(encoding["labels"].dtype  ,    torch.long		)
										self.assertTrue(encoding["labels"].min().item() >= 0		)
										self.assertTrue(encoding["labels"].max().item() <= 255		)

										# Test not batched input (PIL images)
										_UpperCAmelCase						,							_UpperCAmelCase				:						List[Any]       						=			prepare_semantic_single_inputs()

										_UpperCAmelCase				:						Optional[int]       						=			image_processing(A_  ,    A_  ,    return_tensors="pt"		)
										self.assertEqual(
										    encoding["pixel_values"].shape  ,    (
										        1,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(
										    encoding["labels"].shape  ,    (
										        1,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(encoding["labels"].dtype  ,    torch.long		)
										self.assertTrue(encoding["labels"].min().item() >= 0		)
										self.assertTrue(encoding["labels"].max().item() <= 255		)

										# Test batched input (PIL images)
										_UpperCAmelCase						,							_UpperCAmelCase				:						List[str]       						=			prepare_semantic_batch_inputs()

										_UpperCAmelCase				:						int       						=			image_processing(A_  ,    A_  ,    return_tensors="pt"		)
										self.assertEqual(
										    encoding["pixel_values"].shape  ,    (
										        2,
										        self.image_processor_tester.num_channels,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(
										    encoding["labels"].shape  ,    (
										        2,
										        self.image_processor_tester.size["height"],
										        self.image_processor_tester.size["width"],
										    )  ,    )
										self.assertEqual(encoding["labels"].dtype  ,    torch.long		)
										self.assertTrue(encoding["labels"].min().item() >= 0		)
										self.assertTrue(encoding["labels"].max().item() <= 255		)





						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Tuple       						=			self.image_processing_class(**self.image_processor_dict		)

										# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
										_UpperCAmelCase						,							_UpperCAmelCase				:						int       						=			prepare_semantic_single_inputs()
										_UpperCAmelCase				:						Optional[int]       						=			image_processing(A_  ,    A_  ,    return_tensors="pt"		)
										self.assertTrue(encoding["labels"].min().item() >= 0		)
										self.assertTrue(encoding["labels"].max().item() <= 150		)

										_UpperCAmelCase				:						List[Any]       						=			True
										_UpperCAmelCase				:						Optional[Any]       						=			image_processing(A_  ,    A_  ,    return_tensors="pt"		)
										self.assertTrue(encoding["labels"].min().item() >= 0		)
										self.assertTrue(encoding["labels"].max().item() <= 255		)





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


											@staticmethod
											def 				_UpperCAmelCase (				*A_  ,    **A_		):







															'''simple docstring'''


															pass

@is_pipeline_test
@require_torch_or_tf
@require_vision
class  a     (		unittest.TestCase ):
						_lowercase			  =	MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
						_lowercase			  =	TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_  ,    A_		):







										'''simple docstring'''


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


						def 				_UpperCAmelCase (				self  ,    A_  ,    A_		):







										'''simple docstring'''


										_UpperCAmelCase				:						Tuple       						=			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

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

										# Accepts URL + PIL.Image + lists
										_UpperCAmelCase				:						Any       						=			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 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Any       						=			"hf-internal-testing/tiny-random-vit"
										_UpperCAmelCase				:						List[Any]       						=			pipeline("image-classification"  ,    model=A_		)

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

										_UpperCAmelCase				:						List[str]       						=			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_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				:						int       						=			"hf-internal-testing/tiny-random-vit"
										_UpperCAmelCase				:						List[Any]       						=			pipeline("image-classification"  ,    model=A_  ,    framework="tf"		)

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

										_UpperCAmelCase				:						Optional[int]       						=			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_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				:						Optional[Any]       						=			PreTrainedTokenizer()

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

										self.assertIs(image_classifier.tokenizer  ,    A_		)





						@slow
						@require_torch
						def 				_UpperCAmelCase (				self		):







										'''simple docstring'''


										_UpperCAmelCase				:						Dict       						=			pipeline("image-classification"  ,    model="deepmind/vision-perceiver-conv"		)
										_UpperCAmelCase				:						Union[str, Any]       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    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				:						str       						=			pipeline("image-classification"  ,    model="deepmind/vision-perceiver-fourier"		)
										_UpperCAmelCase				:						Optional[int]       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    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				:						List[Any]       						=			pipeline("image-classification"  ,    model="deepmind/vision-perceiver-learned"		)
										_UpperCAmelCase				:						str       						=			image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg"		)
										self.assertEqual(
										    nested_simplify(A_  ,    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"},
										    ]  ,    )


