

'''simple docstring'''



# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re

from ..utils import cached_file


# docstyle-ignore
_UpperCamelCase						:  str							       =				"\nHuman: <<task>>\n\nAssistant: "


_UpperCamelCase						:  Optional[int]							       =				"huggingface-tools/default-prompts"
_UpperCamelCase						:  Optional[Any]							       =				{"chat": "chat_prompt_template.txt", "run": "run_prompt_template.txt"}


def       snake_case   (	snake_case      : int					,		snake_case      : int					,		snake_case      : Optional[int]="run"			) ->  List[Any]:


    """simple docstring"""


    if prompt_or_repo_id is None:
        lowerCAmelCase 						=							DEFAULT_PROMPTS_REPO

    # prompt is considered a repo ID when it does not contain any kind of space
    if re.search('\\s'					,		snake_case			) is not None:
        return prompt_or_repo_id

    lowerCAmelCase 						=							cached_file(
        snake_case					,		PROMPT_FILES[mode]					,		repo_type='dataset'					,		user_agent={'agent': agent_name}			)
    with open(snake_case					,		'r'					,		encoding='utf-8'			) as f:
        return f.read()








'''simple docstring'''



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

_UpperCamelCase						:  Optional[int]							       =				logging.get_logger(__name__)



@add_end_docstrings(a_			)
class 				_snake_case					(   a_			):

  def __init__(				self      , *_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      super().__init__(*_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      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      , _SCREAMING_SNAKE_CASE=None	):





      '''simple docstring'''

      lowerCAmelCase 						=							{}
      if top_k is not None:
          lowerCAmelCase 						=							top_k
      return {}, {}, postprocess_params

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





      '''simple docstring'''

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

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							load_image(_SCREAMING_SNAKE_CASE	)
      lowerCAmelCase 						=							self.image_processor(images=_SCREAMING_SNAKE_CASE      , return_tensors=self.framework	)
      return model_inputs

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model(**_SCREAMING_SNAKE_CASE	)
      return model_outputs


  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=5	):





      '''simple docstring'''

      if top_k > self.model.config.num_labels:
          lowerCAmelCase 						=							self.model.config.num_labels

      if self.framework == "pt":
          lowerCAmelCase 						=							model_outputs.logits.softmax(-1	)[0]
          lowerCAmelCase						,   lowerCAmelCase 						=							probs.topk(_SCREAMING_SNAKE_CASE	)
      elif self.framework == "tf":
          lowerCAmelCase 						=							stable_softmax(model_outputs.logits      , axis=-1	)[0]
          lowerCAmelCase 						=							tf.math.top_k(_SCREAMING_SNAKE_CASE      , k=_SCREAMING_SNAKE_CASE	)
          lowerCAmelCase						,   lowerCAmelCase 						=							topk.values.numpy(), topk.indices.numpy()
      else:
          raise ValueError(F'Unsupported framework: {self.framework}'	)

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





