

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	:



        @staticmethod
        def 			__magic_name__       (				*__A				:	Tuple,						**__A				:	List[Any]		):
          pass





@is_pipeline_test
@require_torch_or_tf
@require_vision
class    __UpperCAmelCase	(			unittest.TestCase		):
   UpperCamelCase  	=	MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
   UpperCamelCase  	=	TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING



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



   def 			__magic_name__       (				self				:	Dict,						__A				:	str,						__A				:	Dict		):
     UpperCAmelCase			:				Union[str, Any]										=					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			:				List[Any]										=					datasets.load_dataset('''hf-internal-testing/fixtures_image_utils''',						'''image''',						split='''test'''		)

     # Accepts URL + PIL.Image + lists
     UpperCAmelCase			:				Dict										=					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 			__magic_name__       (				self				:	Any		):
     UpperCAmelCase			:				int										=					'''hf-internal-testing/tiny-random-vit'''
     UpperCAmelCase			:				Union[str, Any]										=					pipeline('''image-classification''',						model=__A		)

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

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

     UpperCAmelCase			:				str										=					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}],						)

     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_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 			__magic_name__       (				self				:	Optional[Any]		):
     UpperCAmelCase			:				List[str]										=					PreTrainedTokenizer()

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

     self.assertIs(image_classifier.tokenizer,						__A		)





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

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

     UpperCAmelCase			:				List[str]										=					pipeline('''image-classification''',						model='''deepmind/vision-perceiver-learned'''		)
     UpperCAmelCase			:				Union[str, Any]										=					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'''},
         ],						)













"""simple docstring"""







# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
	import tensorflow as tf







class 							_SCREAMING_SNAKE_CASE    (	TensorFormatter[Mapping, 'tf.Tensor', Mapping]				):





							"""simple docstring"""





							def __init__( self:  Union[str, Any]					,		__A:  Union[str, Any]=None					,		**__A:  Union[str, Any]     ):

												'''simple docstring'''

												super().__init__(features=__A     )
												a__ 							=	tf_tensor_kwargs
												import tensorflow as tf  # noqa: import tf at initialization




							def 			lowercase		( self:  Optional[int]					,		__A:  List[Any]     ):

												'''simple docstring'''

												import tensorflow as tf

												if isinstance(__A					,		__A     ) and column:
																	if all(
																	    isinstance(__A					,		tf.Tensor     ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column     ):
																						return tf.stack(__A     )
																	elif all(
																	    isinstance(__A					,		(tf.Tensor, tf.RaggedTensor)     ) and x.ndim == 1 and x.dtype == column[0].dtype
																	    for x in column     ):
																						# only rag 1-D tensors, otherwise some dimensions become ragged even though they were consolidated
																						return tf.ragged.stack(__A     )

												return column




							def 			lowercase		( self:  int					,		__A:  Optional[Any]     ):

												'''simple docstring'''

												import tensorflow as tf

												if value is None:
																	return value

												a__ 							=	{}

												if isinstance(__A					,		(np.number, np.ndarray)     ) and np.issubdtype(value.dtype					,		np.integer     ):
																	a__ 							=	{'''dtype''': tf.intaa}
												elif isinstance(__A					,		(np.number, np.ndarray)     ) and np.issubdtype(value.dtype					,		np.floating     ):
																	a__ 							=	{'''dtype''': tf.floataa}
												elif config.PIL_AVAILABLE and "PIL" in sys.modules:
																	import PIL.Image

																	if isinstance(__A					,		PIL.Image.Image     ):
																						a__ 							=	np.asarray(__A     )

												return tf.convert_to_tensor(__A					,		**{**default_dtype, **self.tf_tensor_kwargs}     )




							def 			lowercase		( self:  List[Any]					,		__A:  str     ):

												'''simple docstring'''

												import tensorflow as tf

												# support for torch, tf, jax etc.
												if config.TORCH_AVAILABLE and "torch" in sys.modules:
																	import torch

																	if isinstance(__A					,		torch.Tensor     ):
																						return self._tensorize(data_struct.detach().cpu().numpy()[()]     )
												if hasattr(__A					,		'''__array__'''     ) and not isinstance(__A					,		tf.Tensor     ):
																	a__ 							=	data_struct.__array__()
												# support for nested types like struct of list of struct
												if isinstance(__A					,		np.ndarray     ):
																	if data_struct.dtype == object:  # tf tensors cannot be instantied from an array of objects
																						return self._consolidate([self.recursive_tensorize(__A     ) for substruct in data_struct]     )
												elif isinstance(__A					,		(list, tuple)     ):
																	return self._consolidate([self.recursive_tensorize(__A     ) for substruct in data_struct]     )
												return self._tensorize(__A     )




							def 			lowercase		( self:  int					,		__A:  dict     ):

												'''simple docstring'''

												return map_nested(self._recursive_tensorize					,		__A					,		map_list=__A     )




							def 			lowercase		( self:  Tuple					,		__A:  pa.Table     ):

												'''simple docstring'''

												a__ 							=	self.numpy_arrow_extractor().extract_row(__A     )
												a__ 							=	self.python_features_decoder.decode_row(__A     )
												return self.recursive_tensorize(__A     )




							def 			lowercase		( self:  Dict					,		__A:  pa.Table     ):

												'''simple docstring'''

												a__ 							=	self.numpy_arrow_extractor().extract_column(__A     )
												a__ 							=	self.python_features_decoder.decode_column(__A					,		pa_table.column_names[0]     )
												a__ 							=	self.recursive_tensorize(__A     )
												a__ 							=	self._consolidate(__A     )
												return column





							def 			lowercase		( self:  Tuple					,		__A:  pa.Table     ):

												'''simple docstring'''

												a__ 							=	self.numpy_arrow_extractor().extract_batch(__A     )
												a__ 							=	self.python_features_decoder.decode_batch(__A     )
												a__ 							=	self.recursive_tensorize(__A     )
												for column_name in batch:
																	a__ 							=	self._consolidate(batch[column_name]     )
												return batch


