import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
def       __magic_name__(  __UpperCAmelCase		)						->    str:



      '''simple docstring'''

      return 1.0 / (1.0 + np.exp(-_outputs		))
def       __magic_name__(  __UpperCAmelCase		)						->    List[str]:



      '''simple docstring'''

      _lowerCamelCase			    =				np.max(_outputs ,						axis=-1 ,						keepdims=__UpperCAmelCase		)
      _lowerCamelCase			    =				np.exp(_outputs - maxes		)
      return shifted_exp / shifted_exp.sum(axis=-1 ,						keepdims=__UpperCAmelCase		)



class  UpperCamelCase				( __lowercase ):

     '''simple docstring'''

     A_										=  'sigmoid'
     A_										=  'softmax'
     A_										=  'none'





@add_end_docstrings(
    __lowercase   ,  R'\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `"default"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `"sigmoid"`: Applies the sigmoid function on the output.\n            - `"softmax"`: Applies the softmax function on the output.\n            - `"none"`: Does not apply any function on the output.\n    '   ,  )
class  UpperCamelCase				( __lowercase ):

     '''simple docstring'''

     A_										=  False
     A_										=  ClassificationFunction.NONE



     def __init__(					self				,				**A_						) ->				str:






           """simple docstring"""
           super().__init__(**A_						)

           self.check_model_type(
               TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
               if self.framework == '''tf'''
               else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING						)



     def 		UpperCamelCase_						(					self				,				A_=None				,				A_=None				,				A_=""				,				**A_						) ->				str:






           """simple docstring"""
           # Using "" as default argument because we're going to use `top_k=None` in user code to declare
           # "No top_k"
           _lowerCamelCase			    =				tokenizer_kwargs

           _lowerCamelCase			    =				{}
           if hasattr(self.model.config				,				'''return_all_scores'''						) and return_all_scores is None:
                 _lowerCamelCase			    =				self.model.config.return_all_scores

           if isinstance(A_				,				A_						) or top_k is None:
                 _lowerCamelCase			    =				top_k
                 _lowerCamelCase			    =				False
           elif return_all_scores is not None:
                 warnings.warn(
                     '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
                     ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''				,				A_				,				)
                 if return_all_scores:
                       _lowerCamelCase			    =				None
                 else:
                       _lowerCamelCase			    =				1

           if isinstance(A_				,				A_						):
                 _lowerCamelCase			    =				ClassificationFunction[function_to_apply.upper()]

           if function_to_apply is not None:
                 _lowerCamelCase			    =				function_to_apply
           return preprocess_params, {}, postprocess_params



     def __call__(					self				,				*A_				,				**A_						) ->				Optional[Any]:






           """simple docstring"""
           _lowerCamelCase			    =				super().__call__(*A_				,				**A_						)
           # TODO try and retrieve it in a nicer way from _sanitize_parameters.
           _lowerCamelCase			    =				'''top_k''' not in kwargs
           if isinstance(args[0]				,				A_						) and _legacy:
                 # This pipeline is odd, and return a list when single item is run
                 return [result]
           else:
                 return result



     def 		UpperCamelCase_						(					self				,				A_				,				**A_						) ->				Dict[str, GenericTensor]:






           """simple docstring"""
           _lowerCamelCase			    =				self.framework
           if isinstance(A_				,				A_						):
                 return self.tokenizer(**A_				,				return_tensors=A_				,				**A_						)
           elif isinstance(A_				,				A_						) and len(A_						) == 1 and isinstance(inputs[0]				,				A_						) and len(inputs[0]						) == 2:
                 # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
                 return self.tokenizer(
                     text=inputs[0][0]				,				text_pair=inputs[0][1]				,				return_tensors=A_				,				**A_						)
           elif isinstance(A_				,				A_						):
                 # This is likely an invalid usage of the pipeline attempting to pass text pairs.
                 raise ValueError(
                     '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
                     ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''						)
           return self.tokenizer(A_				,				return_tensors=A_				,				**A_						)



     def 		UpperCamelCase_						(					self				,				A_						) ->				int:






           """simple docstring"""
           return self.model(**A_						)





     def 		UpperCamelCase_						(					self				,				A_				,				A_=None				,				A_=1				,				A_=True						) ->				List[Any]:






           """simple docstring"""
           # `_legacy` is used to determine if we're running the naked pipeline and in backward
           # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
           # the more natural result containing the list.
           # Default value before `set_parameters`
           if function_to_apply is None:
                 if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                       _lowerCamelCase			    =				ClassificationFunction.SIGMOID
                 elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                       _lowerCamelCase			    =				ClassificationFunction.SOFTMAX
                 elif hasattr(self.model.config				,				'''function_to_apply'''						) and function_to_apply is None:
                       _lowerCamelCase			    =				self.model.config.function_to_apply
                 else:
                       _lowerCamelCase			    =				ClassificationFunction.NONE

           _lowerCamelCase			    =				model_outputs['''logits'''][0]
           _lowerCamelCase			    =				outputs.numpy()

           if function_to_apply == ClassificationFunction.SIGMOID:
                 _lowerCamelCase			    =				sigmoid(A_						)
           elif function_to_apply == ClassificationFunction.SOFTMAX:
                 _lowerCamelCase			    =				softmax(A_						)
           elif function_to_apply == ClassificationFunction.NONE:
                 _lowerCamelCase			    =				outputs
           else:
                 raise ValueError(F'Unrecognized `function_to_apply` argument: {function_to_apply}'						)

           if top_k == 1 and _legacy:
                 return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

           _lowerCamelCase			    =				[
               {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(A_						)
           ]
           if not _legacy:
                 dict_scores.sort(key=lambda A_						: x["score"]				,				reverse=A_						)
                 if top_k is not None:
                       _lowerCamelCase			    =				dict_scores[:top_k]
           return dict_scores
import json
import pathlib
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision, slow
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 YolosImageProcessor



class  UpperCamelCase				( unittest.TestCase ):

     '''simple docstring'''

     def __init__(					self				,				A_				,				A_=7				,				A_=3				,				A_=30				,				A_=4_00				,				A_=True				,				A_=None				,				A_=True				,				A_=[0.5, 0.5, 0.5]				,				A_=[0.5, 0.5, 0.5]				,				A_=True				,				A_=1 / 2_55				,				A_=True				,				) ->				List[Any]:






           """simple docstring"""
           # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
           _lowerCamelCase			    =				size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 13_33}
           _lowerCamelCase			    =				parent
           _lowerCamelCase			    =				batch_size
           _lowerCamelCase			    =				num_channels
           _lowerCamelCase			    =				min_resolution
           _lowerCamelCase			    =				max_resolution
           _lowerCamelCase			    =				do_resize
           _lowerCamelCase			    =				size
           _lowerCamelCase			    =				do_normalize
           _lowerCamelCase			    =				image_mean
           _lowerCamelCase			    =				image_std
           _lowerCamelCase			    =				do_rescale
           _lowerCamelCase			    =				rescale_factor
           _lowerCamelCase			    =				do_pad



     def 		UpperCamelCase_						(					self						) ->				Dict:






           """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_rescale": self.do_rescale,
               "rescale_factor": self.rescale_factor,
               "do_pad": self.do_pad,
           }





     def 		UpperCamelCase_						(					self				,				A_				,				A_=False						) ->				List[str]:






           """simple docstring"""
           if not batched:
                 _lowerCamelCase			    =				image_inputs[0]
                 if isinstance(A_				,				Image.Image						):
                       _lowerCamelCase    ,					_lowerCamelCase			    =				image.size
                 else:
                       _lowerCamelCase    ,					_lowerCamelCase			    =				image.shape[1], image.shape[2]
                 if w < h:
                       _lowerCamelCase			    =				int(self.size['''shortest_edge'''] * h / w						)
                       _lowerCamelCase			    =				self.size['''shortest_edge''']
                 elif w > h:
                       _lowerCamelCase			    =				self.size['''shortest_edge''']
                       _lowerCamelCase			    =				int(self.size['''shortest_edge'''] * w / h						)
                 else:
                       _lowerCamelCase			    =				self.size['''shortest_edge''']
                       _lowerCamelCase			    =				self.size['''shortest_edge''']

           else:
                 _lowerCamelCase			    =				[]
                 for image in image_inputs:
                       _lowerCamelCase    ,					_lowerCamelCase			    =				self.get_expected_values([image]						)
                       expected_values.append((expected_height, expected_width)						)
                 _lowerCamelCase			    =				max(A_				,				key=lambda A_						: item[0]						)[0]
                 _lowerCamelCase			    =				max(A_				,				key=lambda A_						: item[1]						)[1]

           return expected_height, expected_width





@require_torch
@require_vision
class  UpperCamelCase				( __lowercase   ,  unittest.TestCase ):

     '''simple docstring'''

     A_										=  YolosImageProcessor if is_vision_available() else None



     def 		UpperCamelCase_						(					self						) ->				Dict:






           """simple docstring"""
           _lowerCamelCase			    =				YolosImageProcessingTester(self						)



     @property
     def 		UpperCamelCase_						(					self						) ->				Tuple:






           """simple docstring"""
           return self.image_processor_tester.prepare_image_processor_dict()



     def 		UpperCamelCase_						(					self						) ->				List[Any]:






           """simple docstring"""
           _lowerCamelCase			    =				self.image_processing_class(**self.image_processor_dict						)
           self.assertTrue(hasattr(A_				,				'''image_mean'''						)						)
           self.assertTrue(hasattr(A_				,				'''image_std'''						)						)
           self.assertTrue(hasattr(A_				,				'''do_normalize'''						)						)
           self.assertTrue(hasattr(A_				,				'''do_resize'''						)						)
           self.assertTrue(hasattr(A_				,				'''size'''						)						)



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






           """simple docstring"""
           _lowerCamelCase			    =				self.image_processing_class.from_dict(self.image_processor_dict						)
           self.assertEqual(image_processor.size				,				{'''shortest_edge''': 18, '''longest_edge''': 13_33}						)
           self.assertEqual(image_processor.do_pad				,				A_						)

           _lowerCamelCase			    =				self.image_processing_class.from_dict(
               self.image_processor_dict				,				size=42				,				max_size=84				,				pad_and_return_pixel_mask=A_						)
           self.assertEqual(image_processor.size				,				{'''shortest_edge''': 42, '''longest_edge''': 84}						)
           self.assertEqual(image_processor.do_pad				,				A_						)



     def 		UpperCamelCase_						(					self						) ->				Tuple:






           """simple docstring"""
           pass



     def 		UpperCamelCase_						(					self						) ->				Optional[int]:






           """simple docstring"""
           # Initialize image_processing
           _lowerCamelCase			    =				self.image_processing_class(**self.image_processor_dict						)
           # create random PIL images
           _lowerCamelCase			    =				prepare_image_inputs(self.image_processor_tester				,				equal_resolution=A_						)
           for image in image_inputs:
                 self.assertIsInstance(A_				,				Image.Image						)

           # Test not batched input
           _lowerCamelCase			    =				image_processing(image_inputs[0]				,				return_tensors='''pt'''						).pixel_values

           _lowerCamelCase    ,					_lowerCamelCase			    =				self.image_processor_tester.get_expected_values(A_						)

           self.assertEqual(
               encoded_images.shape				,				(1, self.image_processor_tester.num_channels, expected_height, expected_width)				,				)

           # Test batched
           _lowerCamelCase    ,					_lowerCamelCase			    =				self.image_processor_tester.get_expected_values(A_				,				batched=A_						)

           _lowerCamelCase			    =				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,
                   expected_height,
                   expected_width,
               )				,				)



     def 		UpperCamelCase_						(					self						) ->				Any:






           """simple docstring"""
           # Initialize image_processing
           _lowerCamelCase			    =				self.image_processing_class(**self.image_processor_dict						)
           # create random numpy tensors
           _lowerCamelCase			    =				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
           _lowerCamelCase			    =				image_processing(image_inputs[0]				,				return_tensors='''pt'''						).pixel_values

           _lowerCamelCase    ,					_lowerCamelCase			    =				self.image_processor_tester.get_expected_values(A_						)

           self.assertEqual(
               encoded_images.shape				,				(1, self.image_processor_tester.num_channels, expected_height, expected_width)				,				)

           # Test batched
           _lowerCamelCase			    =				image_processing(A_				,				return_tensors='''pt'''						).pixel_values

           _lowerCamelCase    ,					_lowerCamelCase			    =				self.image_processor_tester.get_expected_values(A_				,				batched=A_						)

           self.assertEqual(
               encoded_images.shape				,				(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )				,				)



     def 		UpperCamelCase_						(					self						) ->				Optional[int]:






           """simple docstring"""
           # Initialize image_processing
           _lowerCamelCase			    =				self.image_processing_class(**self.image_processor_dict						)
           # create random PyTorch tensors
           _lowerCamelCase			    =				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
           _lowerCamelCase			    =				image_processing(image_inputs[0]				,				return_tensors='''pt'''						).pixel_values

           _lowerCamelCase    ,					_lowerCamelCase			    =				self.image_processor_tester.get_expected_values(A_						)

           self.assertEqual(
               encoded_images.shape				,				(1, self.image_processor_tester.num_channels, expected_height, expected_width)				,				)

           # Test batched
           _lowerCamelCase			    =				image_processing(A_				,				return_tensors='''pt'''						).pixel_values

           _lowerCamelCase    ,					_lowerCamelCase			    =				self.image_processor_tester.get_expected_values(A_				,				batched=A_						)

           self.assertEqual(
               encoded_images.shape				,				(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   expected_height,
                   expected_width,
               )				,				)



     def 		UpperCamelCase_						(					self						) ->				List[str]:






           """simple docstring"""
           # Initialize image_processings
           _lowerCamelCase			    =				self.image_processing_class(**self.image_processor_dict						)
           _lowerCamelCase			    =				self.image_processing_class(do_resize=A_				,				do_normalize=A_				,				do_rescale=A_						)
           # create random PyTorch tensors
           _lowerCamelCase			    =				prepare_image_inputs(self.image_processor_tester				,				equal_resolution=A_				,				torchify=A_						)
           for image in image_inputs:
                 self.assertIsInstance(A_				,				torch.Tensor						)

           # Test whether the method "pad" and calling the image processor return the same tensors
           _lowerCamelCase			    =				image_processing_a.pad(A_				,				return_tensors='''pt'''						)
           _lowerCamelCase			    =				image_processing_a(A_				,				return_tensors='''pt'''						)

           self.assertTrue(
               torch.allclose(encoded_images_with_method['''pixel_values''']				,				encoded_images['''pixel_values''']				,				atol=1E-4						)						)



     @slow
     def 		UpperCamelCase_						(					self						) ->				Optional[Any]:






           """simple docstring"""
           # prepare image and target
           _lowerCamelCase			    =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
           with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt'''				,				'''r'''						) as f:
                 _lowerCamelCase			    =				json.loads(f.read()						)

           _lowerCamelCase			    =				{'''image_id''': 3_97_69, '''annotations''': target}

           # encode them
           _lowerCamelCase			    =				YolosImageProcessor.from_pretrained('''hustvl/yolos-small'''						)
           _lowerCamelCase			    =				image_processing(images=A_				,				annotations=A_				,				return_tensors='''pt'''						)

           # verify pixel values
           _lowerCamelCase			    =				torch.Size([1, 3, 8_00, 10_66]						)
           self.assertEqual(encoding['''pixel_values'''].shape				,				A_						)

           _lowerCamelCase			    =				torch.tensor([0.2796, 0.3138, 0.3481]						)
           self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3]				,				A_				,				atol=1E-4						)						)

           # verify area
           _lowerCamelCase			    =				torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area''']				,				A_						)						)
           # verify boxes
           _lowerCamelCase			    =				torch.Size([6, 4]						)
           self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape				,				A_						)
           _lowerCamelCase			    =				torch.tensor([0.5503, 0.2765, 0.0604, 0.2215]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0]				,				A_				,				atol=1E-3						)						)
           # verify image_id
           _lowerCamelCase			    =				torch.tensor([3_97_69]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id''']				,				A_						)						)
           # verify is_crowd
           _lowerCamelCase			    =				torch.tensor([0, 0, 0, 0, 0, 0]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd''']				,				A_						)						)
           # verify class_labels
           _lowerCamelCase			    =				torch.tensor([75, 75, 63, 65, 17, 17]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels''']				,				A_						)						)
           # verify orig_size
           _lowerCamelCase			    =				torch.tensor([4_80, 6_40]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size''']				,				A_						)						)
           # verify size
           _lowerCamelCase			    =				torch.tensor([8_00, 10_66]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size''']				,				A_						)						)





     @slow
     def 		UpperCamelCase_						(					self						) ->				Tuple:






           """simple docstring"""
           # prepare image, target and masks_path
           _lowerCamelCase			    =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
           with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt'''				,				'''r'''						) as f:
                 _lowerCamelCase			    =				json.loads(f.read()						)

           _lowerCamelCase			    =				{'''file_name''': '''000000039769.png''', '''image_id''': 3_97_69, '''segments_info''': target}

           _lowerCamelCase			    =				pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic'''						)

           # encode them
           _lowerCamelCase			    =				YolosImageProcessor(format='''coco_panoptic'''						)
           _lowerCamelCase			    =				image_processing(images=A_				,				annotations=A_				,				masks_path=A_				,				return_tensors='''pt'''						)

           # verify pixel values
           _lowerCamelCase			    =				torch.Size([1, 3, 8_00, 10_66]						)
           self.assertEqual(encoding['''pixel_values'''].shape				,				A_						)

           _lowerCamelCase			    =				torch.tensor([0.2796, 0.3138, 0.3481]						)
           self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3]				,				A_				,				atol=1E-4						)						)

           # verify area
           _lowerCamelCase			    =				torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area''']				,				A_						)						)
           # verify boxes
           _lowerCamelCase			    =				torch.Size([6, 4]						)
           self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape				,				A_						)
           _lowerCamelCase			    =				torch.tensor([0.2625, 0.5437, 0.4688, 0.8625]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0]				,				A_				,				atol=1E-3						)						)
           # verify image_id
           _lowerCamelCase			    =				torch.tensor([3_97_69]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id''']				,				A_						)						)
           # verify is_crowd
           _lowerCamelCase			    =				torch.tensor([0, 0, 0, 0, 0, 0]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd''']				,				A_						)						)
           # verify class_labels
           _lowerCamelCase			    =				torch.tensor([17, 17, 63, 75, 75, 93]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels''']				,				A_						)						)
           # verify masks
           _lowerCamelCase			    =				82_28_73
           self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item()				,				A_						)
           # verify orig_size
           _lowerCamelCase			    =				torch.tensor([4_80, 6_40]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size''']				,				A_						)						)
           # verify size
           _lowerCamelCase			    =				torch.tensor([8_00, 10_66]						)
           self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size''']				,				A_						)						)