



'''simple docstring'''






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


UpperCamelCase__:     List[str]										=    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        SCREAMING_SNAKE_CASE(							A__    ):







	"""simple docstring"""






	def   A			(		self    :  str	,    __snake_case    :  GenericTensor	)    ->	np.ndarray:
								if self.framework == "tf":
															UpperCAmelCase				: str											=	tf.where(input_ids == self.tokenizer.mask_token_id	).numpy()
								elif self.framework == "pt":
															UpperCAmelCase				: Union[str, Any]											=	torch.nonzero(input_ids == self.tokenizer.mask_token_id	,    as_tuple=__snake_case	)
								else:
															raise ValueError('''Unsupported framework'''	)
								return masked_index







	def   A			(		self    :  int	,    __snake_case    :  GenericTensor	)    ->	np.ndarray:
								UpperCAmelCase				: List[str]											=	self.get_masked_index(__snake_case	)
								UpperCAmelCase				: Optional[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   A			(		self    :  int	,    __snake_case    :  GenericTensor	)    ->	Union[str, Any]:
								if isinstance(__snake_case	,    __snake_case	):
															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(__snake_case	)







	def   A			(		self    :  Optional[int]	,    __snake_case    :  str	,    __snake_case    :  List[str]=None	,    **__snake_case    :  int	)    ->	Dict[str, GenericTensor]:
								if return_tensors is None:
															UpperCAmelCase				: List[Any]											=	self.framework
								UpperCAmelCase				: Optional[int]											=	self.tokenizer(__snake_case	,    return_tensors=__snake_case	)
								self.ensure_exactly_one_mask_token(__snake_case	)
								return model_inputs







	def   A			(		self    :  str	,    __snake_case    :  Optional[Any]	)    ->	Optional[Any]:
								UpperCAmelCase				: Optional[int]											=	self.model(**__snake_case	)
								UpperCAmelCase				: int											=	model_inputs['''input_ids''']
								return model_outputs







	def   A			(		self    :  Optional[Any]	,    __snake_case    :  List[str]	,    __snake_case    :  int=5	,    __snake_case    :  Union[str, Any]=None	)    ->	Union[str, Any]:
								# Cap top_k if there are targets
								if target_ids is not None and target_ids.shape[0] < top_k:
															UpperCAmelCase				: str											=	target_ids.shape[0]
								UpperCAmelCase				: Optional[int]											=	model_outputs['''input_ids'''][0]
								UpperCAmelCase				: Optional[int]											=	model_outputs['''logits''']

								if self.framework == "tf":
															UpperCAmelCase				: Dict											=	tf.where(input_ids == self.tokenizer.mask_token_id	).numpy()[:, 0]

															UpperCAmelCase				: Dict											=	outputs.numpy()

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

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

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

															UpperCAmelCase							,	UpperCAmelCase				: int											=	probs.topk(__snake_case	)

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

																						UpperCAmelCase				: str											=	p
																						# Filter padding out:
																						UpperCAmelCase				: str											=	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
																						UpperCAmelCase				: Dict											=	self.tokenizer.decode(__snake_case	,    skip_special_tokens=__snake_case	)
																						UpperCAmelCase				: Optional[Any]											=	{'''score''': v, '''token''': p, '''token_str''': self.tokenizer.decode([p]	), '''sequence''': sequence}
																						row.append(__snake_case	)
															result.append(__snake_case	)
								if single_mask:
															return result[0]
								return result







	def   A			(		self    :  List[Any]	,    __snake_case    :  List[str]	,    __snake_case    :  str=None	)    ->	str:
								if isinstance(__snake_case	,    __snake_case	):
															UpperCAmelCase				: List[Any]											=	[targets]
								try:
															UpperCAmelCase				: Union[str, Any]											=	self.tokenizer.get_vocab()
								except Exception:
															UpperCAmelCase				: List[str]											=	{}
								UpperCAmelCase				: Optional[int]											=	[]
								for target in targets:
															UpperCAmelCase				: List[str]											=	vocab.get(__snake_case	,    __snake_case	)
															if id_ is None:
																						UpperCAmelCase				: Any											=	self.tokenizer(
																						    __snake_case	,    add_special_tokens=__snake_case	,    return_attention_mask=__snake_case	,    return_token_type_ids=__snake_case	,    max_length=1	,    truncation=__snake_case	,    )['''input_ids''']
																						if len(__snake_case	) == 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
																						UpperCAmelCase				: Dict											=	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_	)
								UpperCAmelCase				: int											=	list(set(__snake_case	)	)
								if len(__snake_case	) == 0:
															raise ValueError('''At least one target must be provided when passed.'''	)
								UpperCAmelCase				: Any											=	np.array(__snake_case	)
								return target_ids







	def   A			(		self    :  Dict	,    __snake_case    :  List[Any]=None	,    __snake_case    :  str=None	)    ->	int:
								UpperCAmelCase				: List[str]											=	{}

								if targets is not None:
															UpperCAmelCase				: Tuple											=	self.get_target_ids(__snake_case	,    __snake_case	)
															UpperCAmelCase				: List[str]											=	target_ids

								if top_k is not None:
															UpperCAmelCase				: List[Any]											=	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    :  Dict	,    __snake_case    :  List[str]	,    *__snake_case    :  int	,    **__snake_case    :  Dict	)    ->	Optional[Any]:
								UpperCAmelCase				: Tuple											=	super().__call__(__snake_case	,    **__snake_case	)
								if isinstance(__snake_case	,    __snake_case	) and len(__snake_case	) == 1:
															return outputs[0]
								return outputs










'''simple docstring'''






import warnings

from ...utils import logging
from .image_processing_beit import BeitImageProcessor


UpperCamelCase__:     Dict										=    logging.get_logger(__name__)

class        SCREAMING_SNAKE_CASE(							A__    ):







	"""simple docstring"""






	def __init__(		self    :  Optional[Any]	,    *__snake_case    :  List[str]	,    **__snake_case    :  str	)    ->	None:
								warnings.warn(
								    '''The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
								    ''' use BeitImageProcessor instead.'''	,    __snake_case	,    )
								super().__init__(*__snake_case	,    **__snake_case	)





