


"""simple docstring"""

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 							A		(       snake_case   :str	)   ->			Union[str, Any]:
 return 1.0 / (1.0 + np.exp(-_outputs	))






def 							A		(       snake_case   :str	)   ->			int:
 __UpperCamelCase       						= np.max(_outputs       ,      axis=-1       ,      keepdims=__UpperCamelCase	)
 __UpperCamelCase       						= np.exp(_outputs - maxes	)
 return shifted_exp / shifted_exp.sum(axis=-1       ,      keepdims=__UpperCamelCase	)

class __lowerCAmelCase	(   SCREAMING_SNAKE_CASE_    ):
     lowercase		     =		"sigmoid"
     lowercase		     =		"softmax"
     lowercase		     =		"none"


@add_end_docstrings(
    SCREAMING_SNAKE_CASE_    ,						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 __lowerCAmelCase	(   SCREAMING_SNAKE_CASE_    ):
     lowercase		     =		False
     lowercase		     =		ClassificationFunction.NONE





     def __init__(			self			,  **__UpperCAmelCase   ):

      '''simple docstring'''




      super().__init__(**UpperCamelCase__   )

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





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase=None			,  __UpperCAmelCase=None			,  __UpperCAmelCase=""			,  **__UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= tokenizer_kwargs

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

      if isinstance(UpperCamelCase__			,  UpperCamelCase__   ) or top_k is None:
       __UpperCamelCase       						= top_k
       __UpperCamelCase       						= 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`.'			,  UpperCamelCase__			,  )
       if return_all_scores:
        __UpperCamelCase       						= None
       else:
        __UpperCamelCase       						= 1

      if isinstance(UpperCamelCase__			,  UpperCamelCase__   ):
       __UpperCamelCase       						= ClassificationFunction[function_to_apply.upper()]

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





     def __call__(			self			,  *__UpperCAmelCase			,  **__UpperCAmelCase   ):

      '''simple docstring'''




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





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  **__UpperCAmelCase   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.framework
      if isinstance(UpperCamelCase__			,  UpperCamelCase__   ):
       return self.tokenizer(**UpperCamelCase__			,  return_tensors=UpperCamelCase__			,  **UpperCamelCase__   )
      elif isinstance(UpperCamelCase__			,  UpperCamelCase__   ) and len(UpperCamelCase__   ) == 1 and isinstance(inputs[0]			,  UpperCamelCase__   ) 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=UpperCamelCase__			,  **UpperCamelCase__   )
      elif isinstance(UpperCamelCase__			,  UpperCamelCase__   ):
       # 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(UpperCamelCase__			,  return_tensors=UpperCamelCase__			,  **UpperCamelCase__   )





     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase   ):

      '''simple docstring'''




      return self.model(**UpperCamelCase__   )







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  __UpperCAmelCase=None			,  __UpperCAmelCase=1			,  __UpperCAmelCase=True   ):

      '''simple docstring'''




      if function_to_apply is None:
       if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
        __UpperCamelCase       						= ClassificationFunction.SIGMOID
       elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
        __UpperCamelCase       						= ClassificationFunction.SOFTMAX
       elif hasattr(self.model.config			,  'function_to_apply'   ) and function_to_apply is None:
        __UpperCamelCase       						= self.model.config.function_to_apply
       else:
        __UpperCamelCase       						= ClassificationFunction.NONE

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

      if function_to_apply == ClassificationFunction.SIGMOID:
       __UpperCamelCase       						= sigmoid(UpperCamelCase__   )
      elif function_to_apply == ClassificationFunction.SOFTMAX:
       __UpperCamelCase       						= softmax(UpperCamelCase__   )
      elif function_to_apply == ClassificationFunction.NONE:
       __UpperCamelCase       						= 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()}

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





"""simple docstring"""

import unittest
from typing import Dict, List, Optional, Union

import numpy as np

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 BridgeTowerImageProcessor

class __lowerCAmelCase	(   unittest.TestCase    ):





     def __init__(			self			,  __UpperCAmelCase			,  __UpperCAmelCase = True			,  __UpperCAmelCase = None			,  __UpperCAmelCase = 32			,  __UpperCAmelCase = True			,  __UpperCAmelCase = 1 / 255			,  __UpperCAmelCase = True			,  __UpperCAmelCase = True			,  __UpperCAmelCase = [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]			,  __UpperCAmelCase = [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]			,  __UpperCAmelCase = True			,  __UpperCAmelCase=7			,  __UpperCAmelCase=30			,  __UpperCAmelCase=400			,  __UpperCAmelCase=3			,  ):

      '''simple docstring'''




      __UpperCamelCase       						= parent
      __UpperCamelCase       						= do_resize
      __UpperCamelCase       						= size if size is not None else {'shortest_edge': 288}
      __UpperCamelCase       						= size_divisor
      __UpperCamelCase       						= do_rescale
      __UpperCamelCase       						= rescale_factor
      __UpperCamelCase       						= do_normalize
      __UpperCamelCase       						= do_center_crop
      __UpperCamelCase       						= image_mean
      __UpperCamelCase       						= image_std
      __UpperCamelCase       						= do_pad
      __UpperCamelCase       						= batch_size
      __UpperCamelCase       						= num_channels
      __UpperCamelCase       						= min_resolution
      __UpperCamelCase       						= max_resolution





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




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







     def 		UpperCAmelCase      (			self			,  __UpperCAmelCase			,  __UpperCAmelCase=False   ):

      '''simple docstring'''




      if not batched:
       __UpperCamelCase       						= self.size['shortest_edge']
       __UpperCamelCase       						= image_inputs[0]
       if isinstance(__UpperCAmelCase			,  Image.Image   ):
        __UpperCamelCase						,			__UpperCamelCase       						= image.size
       else:
        __UpperCamelCase						,			__UpperCamelCase       						= image.shape[1], image.shape[2]
       __UpperCamelCase       						= size / min(__UpperCAmelCase			,  __UpperCAmelCase   )
       if h < w:
        __UpperCamelCase						,			__UpperCamelCase       						= size, scale * w
       else:
        __UpperCamelCase						,			__UpperCamelCase       						= scale * h, size

       __UpperCamelCase       						= int((1333 / 800) * size   )
       if max(__UpperCAmelCase			,  __UpperCAmelCase   ) > max_size:
        __UpperCamelCase       						= max_size / max(__UpperCAmelCase			,  __UpperCAmelCase   )
        __UpperCamelCase       						= newh * scale
        __UpperCamelCase       						= neww * scale

       __UpperCamelCase						,			__UpperCamelCase       						= int(newh + 0.5   ), int(neww + 0.5   )
       __UpperCamelCase						,			__UpperCamelCase       						= (
           newh // self.size_divisor * self.size_divisor,
           neww // self.size_divisor * self.size_divisor,
       )

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

      return expected_height, expected_width


@require_torch
@require_vision
class __lowerCAmelCase	(   __SCREAMING_SNAKE_CASE    ,						unittest.TestCase    ):
     lowercase		     =		BridgeTowerImageProcessor if is_vision_available() else None





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= BridgeTowerImageProcessingTester(self   )





     @property
     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.image_processing_class(**self.image_processor_dict   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'image_mean'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'image_std'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'do_normalize'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'do_resize'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'size'   )   )
      self.assertTrue(hasattr(__UpperCAmelCase			,  'size_divisor'   )   )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      pass





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.image_processing_class(**self.image_processor_dict   )
      # create random PIL images
      __UpperCamelCase       						= prepare_image_inputs(self.image_processor_tester			,  equal_resolution=__UpperCAmelCase   )
      for image in image_inputs:
       self.assertIsInstance(__UpperCAmelCase			,  Image.Image   )

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

      __UpperCamelCase						,			__UpperCamelCase       						= self.image_processor_tester.get_expected_values(__UpperCAmelCase   )
      self.assertEqual(
          encoded_images.shape			,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)			,  )

      # Test batched
      __UpperCamelCase       						= image_processing(__UpperCAmelCase			,  return_tensors='pt'   ).pixel_values

      __UpperCamelCase						,			__UpperCamelCase       						= self.image_processor_tester.get_expected_values(__UpperCAmelCase			,  batched=__UpperCAmelCase   )
      self.assertEqual(
          encoded_images.shape			,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )			,  )





     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.image_processing_class(**self.image_processor_dict   )
      # create random numpy tensors
      __UpperCamelCase       						= prepare_image_inputs(self.image_processor_tester			,  equal_resolution=__UpperCAmelCase			,  numpify=__UpperCAmelCase   )
      for image in image_inputs:
       self.assertIsInstance(__UpperCAmelCase			,  np.ndarray   )

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

      __UpperCamelCase						,			__UpperCamelCase       						= self.image_processor_tester.get_expected_values(__UpperCAmelCase   )
      self.assertEqual(
          encoded_images.shape			,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)			,  )

      # Test batched
      __UpperCamelCase       						= image_processing(__UpperCAmelCase			,  return_tensors='pt'   ).pixel_values

      __UpperCamelCase						,			__UpperCamelCase       						= self.image_processor_tester.get_expected_values(__UpperCAmelCase			,  batched=__UpperCAmelCase   )
      self.assertEqual(
          encoded_images.shape			,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )			,  )







     def 		UpperCAmelCase      (			self   ):

      '''simple docstring'''




      __UpperCamelCase       						= self.image_processing_class(**self.image_processor_dict   )
      # create random PyTorch tensors
      __UpperCamelCase       						= prepare_image_inputs(self.image_processor_tester			,  equal_resolution=__UpperCAmelCase			,  torchify=__UpperCAmelCase   )
      for image in image_inputs:
       self.assertIsInstance(__UpperCAmelCase			,  torch.Tensor   )

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

      __UpperCamelCase						,			__UpperCamelCase       						= self.image_processor_tester.get_expected_values(__UpperCAmelCase   )
      self.assertEqual(
          encoded_images.shape			,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)			,  )

      # Test batched
      __UpperCamelCase       						= image_processing(__UpperCAmelCase			,  return_tensors='pt'   ).pixel_values

      __UpperCamelCase						,			__UpperCamelCase       						= self.image_processor_tester.get_expected_values(__UpperCAmelCase			,  batched=__UpperCAmelCase   )
      self.assertEqual(
          encoded_images.shape			,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_channels,
              expected_height,
              expected_width,
          )			,  )



