


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	: List[Any]  				=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        _lowercase      (			A__       ):






				'''simple docstring'''



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


				def 		__magic_name__(       self			:Optional[int]			,			lowerCAmelCase__			:GenericTensor	)		->			np.ndarray:
										__SCREAMING_SNAKE_CASE						:     str					=		self.get_masked_index(lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		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 		__magic_name__(       self			:str			,			lowerCAmelCase__			:GenericTensor	)		->			int:
										if isinstance(lowerCAmelCase__			,			lowerCAmelCase__	):
																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(lowerCAmelCase__	)


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


				def 		__magic_name__(       self			:Dict			,			lowerCAmelCase__			:Dict	)		->			Tuple:
										__SCREAMING_SNAKE_CASE						:     Tuple					=		self.model(**lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     Dict					=		model_inputs['''input_ids''']
										return model_outputs


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

										if self.framework == "tf":
																__SCREAMING_SNAKE_CASE						:     List[str]					=		tf.where(input_ids == self.tokenizer.mask_token_id	).numpy()[:, 0]

																__SCREAMING_SNAKE_CASE						:     int					=		outputs.numpy()

																__SCREAMING_SNAKE_CASE						:     Tuple					=		outputs[0, masked_index, :]
																__SCREAMING_SNAKE_CASE						:     List[str]					=		stable_softmax(lowerCAmelCase__			,			axis=-1	)
																if target_ids is not None:
																						__SCREAMING_SNAKE_CASE						:     Dict					=		tf.gather_nd(tf.squeeze(lowerCAmelCase__			,			0	)			,			target_ids.reshape(-1			,			1	)	)
																						__SCREAMING_SNAKE_CASE						:     Optional[int]					=		tf.expand_dims(lowerCAmelCase__			,			0	)

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

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

																__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Optional[int]					=		probs.topk(lowerCAmelCase__	)

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

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


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


				def 		__magic_name__(       self			:Any			,			lowerCAmelCase__			:Tuple=None			,			lowerCAmelCase__			:Optional[Any]=None	)		->			Tuple:
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		{}

										if targets is not None:
																__SCREAMING_SNAKE_CASE						:     Optional[int]					=		self.get_target_ids(lowerCAmelCase__			,			lowerCAmelCase__	)
																__SCREAMING_SNAKE_CASE						:     int					=		target_ids

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




from importlib import import_module

from .logging import get_logger


__lowerCAmelCase	: str  				=get_logger(__name__)
class        _lowercase      :






				'''simple docstring'''



				def __init__(       self			:List[Any]			,			lowerCAmelCase__			:List[Any]			,			lowerCAmelCase__			:str=None	)		->			int:
										__SCREAMING_SNAKE_CASE						:     List[str]					=		attrs or []
										if module is not None:
																for key in module.__dict__:
																						if key in attrs or not key.startswith('''__'''	):
																												setattr(self			,			lowerCAmelCase__			,			getattr(lowerCAmelCase__			,			lowerCAmelCase__	)	)
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		module._original_module if isinstance(lowerCAmelCase__			,			_PatchedModuleObj	) else module




class        _lowercase      :






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			Optional[int]						=		[]


				def __init__(       self			:Tuple			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:str			,			lowerCAmelCase__			:Any			,			lowerCAmelCase__			:Dict=None	)		->			List[Any]:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		obj
										__SCREAMING_SNAKE_CASE						:     str					=		target
										__SCREAMING_SNAKE_CASE						:     Dict					=		new
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		target.split('''.'''	)[0]
										__SCREAMING_SNAKE_CASE						:     List[str]					=		{}
										__SCREAMING_SNAKE_CASE						:     Tuple					=		attrs or []


				def __enter__(       self			:int	)		->			Dict:
										*__SCREAMING_SNAKE_CASE			,			__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		self.target.split('''.'''	)

										# Patch modules:
										# it's used to patch attributes of submodules like "os.path.join";
										# in this case we need to patch "os" and "os.path"

										for i in range(len(lowerCAmelCase__	)	):
																try:
																						__SCREAMING_SNAKE_CASE						:     Any					=		import_module('''.'''.join(submodules[: i + 1]	)	)
																except ModuleNotFoundError:
																						continue
																# We iterate over all the globals in self.obj in case we find "os" or "os.path"
																for attr in self.obj.__dir__():
																						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		getattr(self.obj			,			lowerCAmelCase__	)
																						# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																						# This allows to patch renamed modules like "from os import path as ospath".
																						if obj_attr is submodule or (
																						    (isinstance(lowerCAmelCase__			,			_PatchedModuleObj	) and obj_attr._original_module is submodule)
																						):
																												__SCREAMING_SNAKE_CASE						:     int					=		obj_attr
																												# patch at top level
																												setattr(self.obj			,			lowerCAmelCase__			,			_PatchedModuleObj(lowerCAmelCase__			,			attrs=self.attrs	)	)
																												__SCREAMING_SNAKE_CASE						:     List[str]					=		getattr(self.obj			,			lowerCAmelCase__	)
																												# construct lower levels patches
																												for key in submodules[i + 1 :]:
																																		setattr(lowerCAmelCase__			,			lowerCAmelCase__			,			_PatchedModuleObj(getattr(lowerCAmelCase__			,			lowerCAmelCase__			,			lowerCAmelCase__	)			,			attrs=self.attrs	)	)
																																		__SCREAMING_SNAKE_CASE						:     Tuple					=		getattr(lowerCAmelCase__			,			lowerCAmelCase__	)
																												# finally set the target attribute
																												setattr(lowerCAmelCase__			,			lowerCAmelCase__			,			self.new	)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

										if submodules:  # if it's an attribute of a submodule like "os.path.join"
																try:
																						__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		getattr(import_module('''.'''.join(lowerCAmelCase__	)	)			,			lowerCAmelCase__	)
																except (AttributeError, ModuleNotFoundError):
																						return
																# We iterate over all the globals in self.obj in case we find "os.path.join"
																for attr in self.obj.__dir__():
																						# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																						# This allows to patch renamed attributes like "from os.path import join as pjoin".
																						if getattr(self.obj			,			lowerCAmelCase__	) is attr_value:
																												__SCREAMING_SNAKE_CASE						:     Any					=		getattr(self.obj			,			lowerCAmelCase__	)
																												setattr(self.obj			,			lowerCAmelCase__			,			self.new	)
										elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		globals()['''__builtins__'''][target_attr]
																setattr(self.obj			,			lowerCAmelCase__			,			self.new	)
										else:
																raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''	)


				def __exit__(       self			:str			,			*lowerCAmelCase__			:Union[str, Any]	)		->			Optional[int]:
										for attr in list(self.original	):
																setattr(self.obj			,			lowerCAmelCase__			,			self.original.pop(lowerCAmelCase__	)	)


				def 		__magic_name__(       self			:List[Any]	)		->			List[Any]:
										self.__enter__()
										self._active_patches.append(self	)



				def 		__magic_name__(       self			:Optional[int]	)		->			int:
										try:
																self._active_patches.remove(self	)
										except ValueError:
																# If the patch hasn't been started this will fail
																return None

										return self.__exit__()
