




"""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

_A													=      logging.get_logger(__name__)


@add_end_docstrings(a_						)
class _lowerCamelCase    (					a_						):






   def __init__(		self       :		Optional[Any]   ,     *UpperCamelCase       :		List[str]   ,     **UpperCamelCase       :		Tuple   )			->						Union[str, Any]:

         """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 	_lowerCAmelCase   (		self       :		List[str]   ,     UpperCamelCase       :		str=None   )			->						str:

         """simple docstring"""
         lowerCAmelCase__      :			Tuple   =	{}
         if top_k is not None:
               lowerCAmelCase__      :			Optional[Any]   =	top_k
         return {}, {}, postprocess_params






   def __call__(		self       :		Any   ,     UpperCamelCase       :		Union[str, List[str], "Image.Image", List["Image.Image"]]   ,     **UpperCamelCase       :		List[Any]   )			->						List[str]:

         """simple docstring"""
         return super().__call__(UpperCamelCase   ,     **UpperCamelCase   )






   def 	_lowerCAmelCase   (		self       :		Tuple   ,     UpperCamelCase       :		str   )			->						List[Any]:

         """simple docstring"""
         lowerCAmelCase__      :			int   =	load_image(UpperCamelCase   )
         lowerCAmelCase__      :			List[Any]   =	self.image_processor(images=UpperCamelCase   ,     return_tensors=self.framework   )
         return model_inputs






   def 	_lowerCAmelCase   (		self       :		Dict   ,     UpperCamelCase       :		List[str]   )			->						Union[str, Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Optional[int]   =	self.model(**UpperCamelCase   )
         return model_outputs






   def 	_lowerCAmelCase   (		self       :		Optional[int]   ,     UpperCamelCase       :		List[str]   ,     UpperCamelCase       :		Any=5   )			->						Optional[Any]:

         """simple docstring"""
         if top_k > self.model.config.num_labels:
               lowerCAmelCase__      :			str   =	self.model.config.num_labels

         if self.framework == "pt":
               lowerCAmelCase__      :			str   =	model_outputs.logits.softmax(-1   )[0]
               lowerCAmelCase__ ,   lowerCAmelCase__      :			int   =	probs.topk(UpperCamelCase   )
         elif self.framework == "tf":
               lowerCAmelCase__      :			Union[str, Any]   =	stable_softmax(model_outputs.logits   ,     axis=-1   )[0]
               lowerCAmelCase__      :			Tuple   =	tf.math.top_k(UpperCamelCase   ,     k=UpperCamelCase   )
               lowerCAmelCase__ ,   lowerCAmelCase__      :			Union[str, Any]   =	topk.values.numpy(), topk.indices.numpy()
         else:
               raise ValueError(f"""Unsupported framework: {self.framework}"""   )

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











"""simple docstring"""


import json
import os
from typing import Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_A													=      logging.get_logger(__name__)

_A													=      {"""vocab_file""": """vocab.json"""}

_A													=      {
    """vocab_file""": {
        """mgp-str""": """https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json""",
    }
}

_A													=      {"""mgp-str""": 2_7}


class _lowerCamelCase    (					a_						):
   _lowerCamelCase    :Dict     				=     VOCAB_FILES_NAMES
   _lowerCamelCase    :Union[str, Any]     				=     PRETRAINED_VOCAB_FILES_MAP
   _lowerCamelCase    :Optional[int]     				=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES






   def __init__(		self       :		Optional[int]   ,     UpperCamelCase       :		int   ,     UpperCamelCase       :		Union[str, Any]="[GO]"   ,     UpperCamelCase       :		Any="[GO]"   ,     UpperCamelCase       :		Tuple="[s]"   ,     UpperCamelCase       :		List[Any]="[GO]"   ,     **UpperCamelCase       :		Dict   )			->						Union[str, Any]:

         """simple docstring"""
         super().__init__(
             unk_token=UpperCamelCase   ,     bos_token=UpperCamelCase   ,     eos_token=UpperCamelCase   ,     pad_token=UpperCamelCase   ,     **UpperCamelCase   ,     )

         with open(UpperCamelCase   ,     encoding="""utf-8"""   ) as vocab_handle:
               lowerCAmelCase__      :			Optional[Any]   =	json.load(UpperCamelCase   )
         lowerCAmelCase__      :			Union[str, Any]   =	{v: k for k, v in self.vocab.items()}






   @property
   def 	_lowerCAmelCase   (		self       :		int   )			->						Dict:

         """simple docstring"""
         return len(self.vocab   )






   def 	_lowerCAmelCase   (		self       :		Dict   )			->						Any:

         """simple docstring"""
         return dict(self.vocab   ,     **self.added_tokens_encoder   )






   def 	_lowerCAmelCase   (		self       :		List[Any]   ,     UpperCamelCase       :		Tuple   )			->						Optional[Any]:

         """simple docstring"""
         lowerCAmelCase__      :			Optional[Any]   =	[]
         for s in text:
               char_tokens.extend(UpperCamelCase   )
         return char_tokens






   def 	_lowerCAmelCase   (		self       :		List[Any]   ,     UpperCamelCase       :		str   )			->						Tuple:

         """simple docstring"""
         return self.vocab.get(UpperCamelCase   ,     self.vocab.get(self.unk_token   )   )






   def 	_lowerCAmelCase   (		self       :		List[str]   ,     UpperCamelCase       :		int   )			->						Any:

         """simple docstring"""
         return self.decoder.get(UpperCamelCase   )






   def 	_lowerCAmelCase   (		self       :		Dict   ,     UpperCamelCase       :		str   ,     UpperCamelCase       :		Optional[str] = None   )			->						Tuple[str]:

         """simple docstring"""
         if not os.path.isdir(UpperCamelCase   ):
               logger.error("""Vocabulary path ({}) should be a directory""".format(UpperCamelCase   )   )
               return
         lowerCAmelCase__      :			Union[str, Any]   =	os.path.join(
             UpperCamelCase   ,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]   )

         with open(UpperCamelCase   ,     """w"""   ,     encoding="""utf-8"""   ) as f:
               f.write(json.dumps(self.vocab   ,     indent=2   ,     sort_keys=UpperCamelCase   ,     ensure_ascii=UpperCamelCase   ) + """\n"""   )

         return (vocab_file,)





