



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


A		=						logging.get_logger(__name__)

@add_end_docstrings(
    SCREAMING_SNAKE_CASE__     ,	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       _a  ( SCREAMING_SNAKE_CASE__):



			def 				__lowercase					(			self							:				Tuple   ,	_lowercase							:				GenericTensor		)							->					np.ndarray:
									if self.framework == "tf":
															snake_case   :			Dict						    = tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()
									elif self.framework == "pt":
															snake_case   :			Tuple						    = torch.nonzero(input_ids == self.tokenizer.mask_token_id   ,	as_tuple=_lowercase		)
									else:
															raise ValueError("Unsupported framework"		)
									return masked_index



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



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



			def 				__lowercase					(			self							:				Tuple   ,	_lowercase							:				List[Any]		)							->					int:
									snake_case   :			List[str]						    = self.model(**_lowercase		)
									snake_case   :			Optional[Any]						    = model_inputs["input_ids"]
									return model_outputs



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

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

															snake_case   :			Union[str, Any]						    = outputs.numpy()

															snake_case   :			Tuple						    = outputs[0, masked_index, :]
															snake_case   :			Union[str, Any]						    = stable_softmax(_lowercase   ,	axis=-1		)
															if target_ids is not None:
																					snake_case   :			Optional[Any]						    = tf.gather_nd(tf.squeeze(_lowercase   ,	0		)   ,	target_ids.reshape(-1   ,	1		)		)
																					snake_case   :			int						    = tf.expand_dims(_lowercase   ,	0		)

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

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

															snake_case    ,			snake_case   :			Optional[Any]						    = probs.topk(_lowercase		)

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

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



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



			def 				__lowercase					(			self							:				str   ,	_lowercase							:				Union[str, Any]=None   ,	_lowercase							:				Dict=None		)							->					List[Any]:
									snake_case   :			Optional[int]						    = {}

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

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








"""simple docstring"""







A		=						8.31_4462  # Unit - J mol-1 K-1

def  __SCREAMING_SNAKE_CASE		(			lowerCamelCase_:							float     ,		lowerCamelCase_:							float     ,		lowerCamelCase_:							float ):
						"""simple docstring"""






						if moles < 0 or kelvin < 0 or volume < 0:
												raise ValueError("Invalid inputs. Enter positive value." )
						return moles * kelvin * UNIVERSAL_GAS_CONSTANT / volume

def  __SCREAMING_SNAKE_CASE		(			lowerCamelCase_:							float     ,		lowerCamelCase_:							float     ,		lowerCamelCase_:							float ):
						"""simple docstring"""






						if moles < 0 or kelvin < 0 or pressure < 0:
												raise ValueError("Invalid inputs. Enter positive value." )
						return moles * kelvin * UNIVERSAL_GAS_CONSTANT / pressure


if __name__ == "__main__":
			from doctest import testmod

			testmod()



