




'''simple docstring'''





import json
import os
import tempfile

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


if is_torch_available():
       import numpy as np
       import torch

if is_vision_available():
       from PIL import Image


def 					UpperCamelCase						(	snake_case						,  snake_case=False						,  snake_case=False						,  snake_case=False ):




   '''simple docstring'''

   assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

   SCREAMING_SNAKE_CASE__      :					str							    =			[]
   for i in range(image_processor_tester.batch_size ):
      if equal_resolution:
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			image_processor_tester.max_resolution
      else:
         # To avoid getting image width/height 0
         SCREAMING_SNAKE_CASE__      :					str							    =			image_processor_tester.min_resolution
         if getattr(snake_case						,  '''size_divisor'''						,  snake_case ):
            # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor`
            SCREAMING_SNAKE_CASE__      :					Dict							    =			max(image_processor_tester.size_divisor						,  snake_case )
         SCREAMING_SNAKE_CASE__    ,					SCREAMING_SNAKE_CASE__      :					Any							    =			np.random.choice(np.arange(snake_case						,  image_processor_tester.max_resolution )						,  2 )
      image_inputs.append(
          np.random.randint(2_55						,  size=(image_processor_tester.num_channels, width, height)						,  dtype=np.uinta ) )

   if not numpify and not torchify:
      # PIL expects the channel dimension as last dimension
      SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			[Image.fromarray(np.moveaxis(snake_case						,  0						,  -1 ) ) for image in image_inputs]

   if torchify:
      SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			[torch.from_numpy(snake_case ) for image in image_inputs]

   return image_inputs


def 					UpperCamelCase						(	snake_case						,  snake_case=10						,  snake_case=10						,  snake_case=False						,  snake_case=False ):




   '''simple docstring'''

   SCREAMING_SNAKE_CASE__      :					int							    =			[]
   for i in range(image_processor_tester.num_frames ):
      video.append(np.random.randint(2_55						,  size=(image_processor_tester.num_channels, width, height)						,  dtype=np.uinta ) )

   if not numpify and not torchify:
      # PIL expects the channel dimension as last dimension
      SCREAMING_SNAKE_CASE__      :					Union[str, Any]							    =			[Image.fromarray(np.moveaxis(snake_case						,  0						,  -1 ) ) for frame in video]

   if torchify:
      SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			[torch.from_numpy(snake_case ) for frame in video]

   return video


def 					UpperCamelCase						(	snake_case						,  snake_case=False						,  snake_case=False						,  snake_case=False ):




   '''simple docstring'''

   assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

   SCREAMING_SNAKE_CASE__      :					Any							    =			[]
   for i in range(image_processor_tester.batch_size ):
      if equal_resolution:
         SCREAMING_SNAKE_CASE__      :					List[str]							    =			image_processor_tester.max_resolution
      else:
         SCREAMING_SNAKE_CASE__    ,					SCREAMING_SNAKE_CASE__      :					Any							    =			np.random.choice(
             np.arange(image_processor_tester.min_resolution						,  image_processor_tester.max_resolution )						,  2 )
         SCREAMING_SNAKE_CASE__      :					Dict							    =			prepare_video(
             image_processor_tester=snake_case						,  width=snake_case						,  height=snake_case						,  numpify=snake_case						,  torchify=snake_case						,  )
      video_inputs.append(snake_case )

   return video_inputs







class     lowercase  :
      __lowercase					=	None






      def  A__(self       )							-> Dict:
         SCREAMING_SNAKE_CASE__      :					Any							    =			self.image_processing_class(**self.image_processor_dict       )
         SCREAMING_SNAKE_CASE__      :					str							    =			json.loads(image_processor.to_json_string()       )
         for key, value in self.image_processor_dict.items():
            self.assertEqual(obj[key]			,	a__       )






      def  A__(self       )							-> List[Any]:
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			self.image_processing_class(**self.image_processor_dict       )

         with tempfile.TemporaryDirectory() as tmpdirname:
            SCREAMING_SNAKE_CASE__      :					int							    =			os.path.join(a__			,	'''image_processor.json'''       )
            image_processor_first.to_json_file(a__       )
            SCREAMING_SNAKE_CASE__      :					Tuple							    =			self.image_processing_class.from_json_file(a__       )

         self.assertEqual(image_processor_second.to_dict()			,	image_processor_first.to_dict()       )






      def  A__(self       )							-> int:
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			self.image_processing_class(**self.image_processor_dict       )

         with tempfile.TemporaryDirectory() as tmpdirname:
            SCREAMING_SNAKE_CASE__      :					Any							    =			image_processor_first.save_pretrained(a__       )[0]
            check_json_file_has_correct_format(a__       )
            SCREAMING_SNAKE_CASE__      :					Union[str, Any]							    =			self.image_processing_class.from_pretrained(a__       )

         self.assertEqual(image_processor_second.to_dict()			,	image_processor_first.to_dict()       )






      def  A__(self       )							-> List[str]:
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			self.image_processing_class()
         self.assertIsNotNone(a__       )






      @require_torch
      @require_vision
      def  A__(self       )							-> str:
         if self.test_cast_dtype is not None:
            # Initialize image_processor
            SCREAMING_SNAKE_CASE__      :					Tuple							    =			self.image_processing_class(**self.image_processor_dict       )

            # create random PyTorch tensors
            SCREAMING_SNAKE_CASE__      :					Any							    =			prepare_image_inputs(self.image_processor_tester			,	equal_resolution=a__			,	torchify=a__       )

            SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			image_processor(a__			,	return_tensors='''pt'''       )
            # for layoutLM compatiblity
            self.assertEqual(encoding.pixel_values.device			,	torch.device('''cpu'''       )       )
            self.assertEqual(encoding.pixel_values.dtype			,	torch.floataa       )

            SCREAMING_SNAKE_CASE__      :					List[Any]							    =			image_processor(a__			,	return_tensors='''pt'''       ).to(torch.floataa       )
            self.assertEqual(encoding.pixel_values.device			,	torch.device('''cpu'''       )       )
            self.assertEqual(encoding.pixel_values.dtype			,	torch.floataa       )

            SCREAMING_SNAKE_CASE__      :					Dict							    =			image_processor(a__			,	return_tensors='''pt'''       ).to('''cpu'''			,	torch.bfloataa       )
            self.assertEqual(encoding.pixel_values.device			,	torch.device('''cpu'''       )       )
            self.assertEqual(encoding.pixel_values.dtype			,	torch.bfloataa       )

            with self.assertRaises(a__       ):
               SCREAMING_SNAKE_CASE__      :					Any							    =			image_processor(a__			,	return_tensors='''pt'''       ).to(torch.bfloataa			,	'''cpu'''       )

            # Try with text + image feature
            SCREAMING_SNAKE_CASE__      :					Tuple							    =			image_processor(a__			,	return_tensors='''pt'''       )
            encoding.update({'''input_ids''': torch.LongTensor([[1, 2, 3], [4, 5, 6]]       )}       )
            SCREAMING_SNAKE_CASE__      :					Dict							    =			encoding.to(torch.floataa       )

            self.assertEqual(encoding.pixel_values.device			,	torch.device('''cpu'''       )       )
            self.assertEqual(encoding.pixel_values.dtype			,	torch.floataa       )
            self.assertEqual(encoding.input_ids.dtype			,	torch.long       )







'''simple docstring'''





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






             @staticmethod
             def  A__(*a__			,	**a__       )							-> Union[str, Any]:
                pass






@is_pipeline_test
@require_torch_or_tf
@require_vision
class     lowercase  ( unittest.TestCase):
      __lowercase					=	MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
      __lowercase					=	TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING






      def  A__(self			,	a__			,	a__			,	a__       )							-> Dict:
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			ImageClassificationPipeline(model=a__			,	image_processor=a__			,	top_k=2       )
         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			[
             Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       ),
             '''http://images.cocodataset.org/val2017/000000039769.jpg''',
         ]
         return image_classifier, examples






      def  A__(self			,	a__			,	a__       )							-> List[Any]:
         SCREAMING_SNAKE_CASE__      :					int							    =			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

         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			datasets.load_dataset('''hf-internal-testing/fixtures_image_utils'''			,	'''image'''			,	split='''test'''       )

         # Accepts URL + PIL.Image + lists
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			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  A__(self       )							-> List[str]:
         SCREAMING_SNAKE_CASE__      :					List[str]							    =			'''hf-internal-testing/tiny-random-vit'''
         SCREAMING_SNAKE_CASE__      :					Any							    =			pipeline('''image-classification'''			,	model=a__       )

         SCREAMING_SNAKE_CASE__      :					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}]			,	)

         SCREAMING_SNAKE_CASE__      :					Any							    =			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  A__(self       )							-> Optional[int]:
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			'''hf-internal-testing/tiny-random-vit'''
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			pipeline('''image-classification'''			,	model=a__			,	framework='''tf'''       )

         SCREAMING_SNAKE_CASE__      :					List[str]							    =			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}]			,	)

         SCREAMING_SNAKE_CASE__      :					Dict							    =			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  A__(self       )							-> Union[str, Any]:
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			PreTrainedTokenizer()

         # Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			pipeline(
             '''image-classification'''			,	model='''hf-internal-testing/tiny-random-vit'''			,	tokenizer=a__       )

         self.assertIs(image_classifier.tokenizer			,	a__       )






      @slow
      @require_torch
      def  A__(self       )							-> int:
         # 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
         SCREAMING_SNAKE_CASE__      :					Union[str, Any]							    =			pipeline('''image-classification'''			,	model='''deepmind/vision-perceiver-conv'''       )
         SCREAMING_SNAKE_CASE__      :					str							    =			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'''},
             ]			,	)

         SCREAMING_SNAKE_CASE__      :					str							    =			pipeline('''image-classification'''			,	model='''deepmind/vision-perceiver-fourier'''       )
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			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'''},
             ]			,	)

         SCREAMING_SNAKE_CASE__      :					Dict							    =			pipeline('''image-classification'''			,	model='''deepmind/vision-perceiver-learned'''       )
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			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'''},
             ]			,	)

