'''simple docstring'''





import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union

from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings


lowerCAmelCase			:							Optional[int]     =logging.getLogger(__name__)




@dataclass
@add_start_docstrings(TrainingArguments.__doc__		)
class 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






      _snake_case    		=       field(default=__lowerCAmelCase ,  metadata={'help': 'Whether to use SortishSampler or not.'}		)
      _snake_case    		=       field(
          default=__lowerCAmelCase ,  metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'}		)
      _snake_case    		=       field(
          default=__lowerCAmelCase ,  metadata={
              'help': (
                  'The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '
                  'to the `max_length` value of the model configuration.'
              )
          } ,  )
      _snake_case    		=       field(
          default=__lowerCAmelCase ,  metadata={
              'help': (
                  'The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '
                  'to the `num_beams` value of the model configuration.'
              )
          } ,  )
      _snake_case    		=       field(
          default=__lowerCAmelCase ,  metadata={
              'help': 'Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'
          } ,  )



      def 	_SCREAMING_SNAKE_CASE    (					self     :				str)				->Tuple:


          """simple docstring"""


          _lowerCamelCase     :		int 						=						super().to_dict()
          for k, v in d.items():
              if isinstance(_UpperCamelCase    ,  _UpperCamelCase):
                  _lowerCamelCase     :		List[Any] 						=						v.to_dict()
          return d





from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
    from PIL import Image

    from ..image_utils import load_image

if is_tf_available():
    import tensorflow as tf

    from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
    from ..tf_utils import stable_softmax

if is_torch_available():
    from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

lowerCAmelCase			:							Optional[Any]     =logging.get_logger(__name__)




@add_end_docstrings(__lowerCAmelCase		)
class 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






      def __init__(					self     :				str    ,  *_UpperCamelCase     :				int    ,  **_UpperCamelCase     :				List[str])				->Tuple:


          """simple docstring"""


          super().__init__(*_UpperCamelCase    ,  **_UpperCamelCase)
          requires_backends(self    ,  """vision""")
          self.check_model_type(
              TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
              if self.framework == """tf"""
              else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict    ,  _UpperCamelCase     :				List[str]=None)				->Optional[int]:


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						{}
          if top_k is not None:
              _lowerCamelCase     :		str 						=						top_k
          return {}, {}, postprocess_params



      def __call__(					self     :				Optional[int]    ,  _UpperCamelCase     :				Union[str, List[str], "Image.Image", List["Image.Image"]]    ,  **_UpperCamelCase     :				Optional[int])				->Dict:


          """simple docstring"""


          return super().__call__(_UpperCamelCase    ,  **_UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[int]    ,  _UpperCamelCase     :				Optional[int])				->str:


          """simple docstring"""


          _lowerCamelCase     :		Tuple 						=						load_image(_UpperCamelCase)
          _lowerCamelCase     :		Any 						=						self.image_processor(images=_UpperCamelCase    ,  return_tensors=self.framework)
          return model_inputs



      def 	_SCREAMING_SNAKE_CASE    (					self     :				str    ,  _UpperCamelCase     :				Union[str, Any])				->List[str]:


          """simple docstring"""


          _lowerCamelCase     :		Any 						=						self.model(**_UpperCamelCase)
          return model_outputs




      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any]    ,  _UpperCamelCase     :				List[str]    ,  _UpperCamelCase     :				List[str]=5)				->str:


          """simple docstring"""


          if top_k > self.model.config.num_labels:
              _lowerCamelCase     :		Union[str, Any] 						=						self.model.config.num_labels

          if self.framework == "pt":
              _lowerCamelCase     :		Optional[Any] 						=						model_outputs.logits.softmax(-1)[0]
              _lowerCamelCase						,							_lowerCamelCase     :		Dict 						=						probs.topk(_UpperCamelCase)
          elif self.framework == "tf":
              _lowerCamelCase     :		List[Any] 						=						stable_softmax(model_outputs.logits    ,  axis=-1)[0]
              _lowerCamelCase     :		List[Any] 						=						tf.math.top_k(_UpperCamelCase    ,  k=_UpperCamelCase)
              _lowerCamelCase						,							_lowerCamelCase     :		str 						=						topk.values.numpy(), topk.indices.numpy()
          else:
              raise ValueError(F"""Unsupported framework: {self.framework}""")

          _lowerCamelCase     :		str 						=						scores.tolist()
          _lowerCamelCase     :		str 						=						ids.tolist()
          return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_UpperCamelCase    ,  _UpperCamelCase)]




