





from typing import Dict

import numpy as np

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


if is_tf_available():
	import tensorflow as tf

	from ..tf_utils import stable_softmax


if is_torch_available():
	import torch


lowerCAmelCase_        =							logging.get_logger(__name__)



@add_end_docstrings(
    _a,	r'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    ''',	)
class    __lowerCAmelCase			(     _a	):






			def      lowerCamelCase    (self   ,				__magic_name__       )	->  np.ndarray:


							'''simple docstring'''



							if self.framework == "tf":
											snake_case_		:       str           =    tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
							elif self.framework == "pt":
											snake_case_		:       Dict           =    torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,				as_tuple=__magic_name__       )
							else:
											raise ValueError('''Unsupported framework'''       )
							return masked_index






			def      lowerCamelCase    (self   ,				__magic_name__       )	->  np.ndarray:


							'''simple docstring'''



							snake_case_		:       Tuple           =    self.get_masked_index(__magic_name__       )
							snake_case_		:       int           =    np.prod(masked_index.shape       )
							if numel < 1:
											raise PipelineException(
											    '''fill-mask'''   ,				self.model.base_model_prefix   ,				F'''No mask_token ({self.tokenizer.mask_token}) found on the input'''   ,				)






			def      lowerCamelCase    (self   ,				__magic_name__       )	->  Tuple:


							'''simple docstring'''



							if isinstance(__magic_name__   ,				__magic_name__       ):
											for model_input in model_inputs:
															self._ensure_exactly_one_mask_token(model_input['''input_ids'''][0]       )
							else:
											for input_ids in model_inputs["input_ids"]:
															self._ensure_exactly_one_mask_token(__magic_name__       )






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__=None   ,				**__magic_name__       )	->  Dict[str, GenericTensor]:


							'''simple docstring'''



							if return_tensors is None:
											snake_case_		:       Tuple           =    self.framework
							snake_case_		:       int           =    self.tokenizer(__magic_name__   ,				return_tensors=__magic_name__       )
							self.ensure_exactly_one_mask_token(__magic_name__       )
							return model_inputs






			def      lowerCamelCase    (self   ,				__magic_name__       )	->  Optional[Any]:


							'''simple docstring'''



							snake_case_		:       Union[str, Any]           =    self.model(**__magic_name__       )
							snake_case_		:       List[Any]           =    model_inputs['''input_ids''']
							return model_outputs






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__=5   ,				__magic_name__=None       )	->  Optional[int]:


							'''simple docstring'''



							if target_ids is not None and target_ids.shape[0] < top_k:
											snake_case_		:       Tuple           =    target_ids.shape[0]
							snake_case_		:       Tuple           =    model_outputs['''input_ids'''][0]
							snake_case_		:       Tuple           =    model_outputs['''logits''']

							if self.framework == "tf":
											snake_case_		:       Optional[int]           =    tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()[:, 0]

											snake_case_		:       Optional[Any]           =    outputs.numpy()

											snake_case_		:       Any           =    outputs[0, masked_index, :]
											snake_case_		:       List[Any]           =    stable_softmax(__magic_name__   ,				axis=-1       )
											if target_ids is not None:
															snake_case_		:       Union[str, Any]           =    tf.gather_nd(tf.squeeze(__magic_name__   ,				0       )   ,				target_ids.reshape(-1   ,				1       )       )
															snake_case_		:       Dict           =    tf.expand_dims(__magic_name__   ,				0       )

											snake_case_		:       Dict           =    tf.math.top_k(__magic_name__   ,				k=__magic_name__       )
											snake_case_     ,				snake_case_		:       Dict           =    topk.values.numpy(), topk.indices.numpy()
							else:
											snake_case_		:       Any           =    torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,				as_tuple=__magic_name__       ).squeeze(-1       )
											# Fill mask pipeline supports only one ${mask_token} per sample

											snake_case_		:       int           =    outputs[0, masked_index, :]
											snake_case_		:       Union[str, Any]           =    logits.softmax(dim=-1       )
											if target_ids is not None:
															snake_case_		:       Optional[Any]           =    probs[..., target_ids]

											snake_case_     ,				snake_case_		:       int           =    probs.topk(__magic_name__       )

							snake_case_		:       Dict           =    []
							snake_case_		:       Dict           =    values.shape[0] == 1
							for i, (_values, _predictions) in enumerate(zip(values.tolist()   ,				predictions.tolist()       )       ):
											snake_case_		:       Optional[Any]           =    []
											for v, p in zip(_values   ,				_predictions       ):
															# Copy is important since we're going to modify this array in place
															snake_case_		:       int           =    input_ids.numpy().copy()
															if target_ids is not None:
																			snake_case_		:       str           =    target_ids[p].tolist()

															snake_case_		:       Union[str, Any]           =    p
															# Filter padding out:
															snake_case_		:       int           =    tokens[np.where(tokens != self.tokenizer.pad_token_id       )]
															# Originally we skip special tokens to give readable output.
															# For multi masks though, the other [MASK] would be removed otherwise
															# making the output look odd, so we add them back
															snake_case_		:       Tuple           =    self.tokenizer.decode(__magic_name__   ,				skip_special_tokens=__magic_name__       )
															snake_case_		:       int           =    {'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]       ), '''sequence''': sequence}
															row.append(__magic_name__       )
											result.append(__magic_name__       )
							if single_mask:
											return result[0]
							return result






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__=None       )	->  List[Any]:


							'''simple docstring'''



							if isinstance(__magic_name__   ,				__magic_name__       ):
											snake_case_		:       List[str]           =    [targets]
							try:
											snake_case_		:       str           =    self.tokenizer.get_vocab()
							except Exception:
											snake_case_		:       Tuple           =    {}
							snake_case_		:       str           =    []
							for target in targets:
											snake_case_		:       int           =    vocab.get(__magic_name__   ,				__magic_name__       )
											if id_ is None:
															snake_case_		:       int           =    self.tokenizer(
															    __magic_name__   ,				add_special_tokens=__magic_name__   ,				return_attention_mask=__magic_name__   ,				return_token_type_ids=__magic_name__   ,				max_length=1   ,				truncation=__magic_name__   ,				)['''input_ids''']
															if len(__magic_name__       ) == 0:
																			logger.warning(
																			    F'''The specified target token `{target}` does not exist in the model vocabulary. '''
																			    '''We cannot replace it with anything meaningful, ignoring it'''       )
																			continue
															snake_case_		:       List[Any]           =    input_ids[0]
															# XXX: If users encounter this pass
															# it becomes pretty slow, so let's make sure
															# The warning enables them to fix the input to
															# get faster performance.
															logger.warning(
															    F'''The specified target token `{target}` does not exist in the model vocabulary. '''
															    F'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_       )}`.'''       )
											target_ids.append(id_       )
							snake_case_		:       Any           =    list(set(__magic_name__       )       )
							if len(__magic_name__       ) == 0:
											raise ValueError('''At least one target must be provided when passed.'''       )
							snake_case_		:       Optional[int]           =    np.array(__magic_name__       )
							return target_ids






			def      lowerCamelCase    (self   ,				__magic_name__=None   ,				__magic_name__=None       )	->  str:


							'''simple docstring'''



							snake_case_		:       str           =    {}

							if targets is not None:
											snake_case_		:       str           =    self.get_target_ids(__magic_name__   ,				__magic_name__       )
											snake_case_		:       Dict           =    target_ids

							if top_k is not None:
											snake_case_		:       Optional[int]           =    top_k

							if self.tokenizer.mask_token_id is None:
											raise PipelineException(
											    '''fill-mask'''   ,				self.model.base_model_prefix   ,				'''The tokenizer does not define a `mask_token`.'''       )
							return {}, {}, postprocess_params






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


							'''simple docstring'''



							snake_case_		:       Dict           =    super().__call__(__magic_name__   ,				**__magic_name__       )
							if isinstance(__magic_name__   ,				__magic_name__       ) and len(__magic_name__       ) == 1:
											return outputs[0]
							return outputs








'''simple docstring'''
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


UpperCamelCase__			=      {
    'configuration_layoutlmv3': [
        'LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'LayoutLMv3Config',
        'LayoutLMv3OnnxConfig',
    ],
    'processing_layoutlmv3': ['LayoutLMv3Processor'],
    'tokenization_layoutlmv3': ['LayoutLMv3Tokenizer'],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      ['LayoutLMv3TokenizerFast']

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      [
     'LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST',
     'LayoutLMv3ForQuestionAnswering',
     'LayoutLMv3ForSequenceClassification',
     'LayoutLMv3ForTokenClassification',
     'LayoutLMv3Model',
     'LayoutLMv3PreTrainedModel',
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      [
     'TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST',
     'TFLayoutLMv3ForQuestionAnswering',
     'TFLayoutLMv3ForSequenceClassification',
     'TFLayoutLMv3ForTokenClassification',
     'TFLayoutLMv3Model',
     'TFLayoutLMv3PreTrainedModel',
 ]

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCamelCase__			=      ['LayoutLMv3FeatureExtractor']
 UpperCamelCase__			=      ['LayoutLMv3ImageProcessor']


if TYPE_CHECKING:
 from .configuration_layoutlmva import (
     LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
     LayoutLMvaConfig,
     LayoutLMvaOnnxConfig,
 )
 from .processing_layoutlmva import LayoutLMvaProcessor
 from .tokenization_layoutlmva import LayoutLMvaTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_layoutlmva import (
      LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      LayoutLMvaForQuestionAnswering,
      LayoutLMvaForSequenceClassification,
      LayoutLMvaForTokenClassification,
      LayoutLMvaModel,
      LayoutLMvaPreTrainedModel,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_layoutlmva import (
      TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFLayoutLMvaForQuestionAnswering,
      TFLayoutLMvaForSequenceClassification,
      TFLayoutLMvaForTokenClassification,
      TFLayoutLMvaModel,
      TFLayoutLMvaPreTrainedModel,
  )

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
  from .image_processing_layoutlmva import LayoutLMvaImageProcessor

else:
 import sys

 UpperCamelCase__			=      _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)




