






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


lowerCamelCase_				: Optional[int]    	=							logging.get_logger(__name__)
@add_end_docstrings(
    SCREAMING_SNAKE_CASE       ,R"\n        top_k (`int`, defaults to 5):\n            The number of predictions to return.\n        targets (`str` or `List[str]`, *optional*):\n            When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n            token will be used (with a warning, and that might be slower).\n\n    "       ,)
class    _SCREAMING_SNAKE_CASE							(		SCREAMING_SNAKE_CASE	):


			'''simple docstring'''





			def 				A      (   self							:						str ,      lowercase							:						GenericTensor			)							->    np.ndarray:

									'''simple docstring'''







									if self.framework == "tf":
															UpperCamelCase__         = tf.where(input_ids == self.tokenizer.mask_token_id			).numpy()
									elif self.framework == "pt":
															UpperCamelCase__         = torch.nonzero(input_ids == self.tokenizer.mask_token_id ,      as_tuple=lowercase			)
									else:
															raise ValueError("""Unsupported framework"""			)
									return masked_index






			def 				A      (   self							:						Tuple ,      lowercase							:						GenericTensor			)							->    np.ndarray:

									'''simple docstring'''







									UpperCamelCase__         = self.get_masked_index(lowercase			)
									UpperCamelCase__         = 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							:						Union[str, Any] ,      lowercase							:						GenericTensor			)							->    List[Any]:

									'''simple docstring'''







									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 				A      (   self							:						Tuple ,      lowercase							:						str ,      lowercase							:						Optional[int]=None ,      **lowercase							:						str			)							->    Dict[str, GenericTensor]:

									'''simple docstring'''







									if return_tensors is None:
															UpperCamelCase__         = self.framework
									UpperCamelCase__         = self.tokenizer(lowercase ,      return_tensors=lowercase			)
									self.ensure_exactly_one_mask_token(lowercase			)
									return model_inputs






			def 				A      (   self							:						str ,      lowercase							:						Tuple			)							->    Optional[int]:

									'''simple docstring'''







									UpperCamelCase__         = self.model(**lowercase			)
									UpperCamelCase__         = model_inputs["""input_ids"""]
									return model_outputs






			def 				A      (   self							:						int ,      lowercase							:						Tuple ,      lowercase							:						Dict=5 ,      lowercase							:						Tuple=None			)							->    Optional[Any]:

									'''simple docstring'''







									if target_ids is not None and target_ids.shape[0] < top_k:
															UpperCamelCase__         = target_ids.shape[0]
									UpperCamelCase__         = model_outputs["""input_ids"""][0]
									UpperCamelCase__         = model_outputs["""logits"""]

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

															UpperCamelCase__         = outputs.numpy()

															UpperCamelCase__         = outputs[0, masked_index, :]
															UpperCamelCase__         = stable_softmax(lowercase ,      axis=-1			)
															if target_ids is not None:
																					UpperCamelCase__         = tf.gather_nd(tf.squeeze(lowercase ,      0			) ,      target_ids.reshape(-1 ,      1			)			)
																					UpperCamelCase__         = tf.expand_dims(lowercase ,      0			)

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

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

															UpperCamelCase__    ,   UpperCamelCase__         = probs.topk(lowercase			)

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

																					UpperCamelCase__         = p
																					# Filter padding out:
																					UpperCamelCase__         = 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__         = self.tokenizer.decode(lowercase ,      skip_special_tokens=lowercase			)
																					UpperCamelCase__         = {"""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 				A      (   self							:						Optional[int] ,      lowercase							:						Optional[Any] ,      lowercase							:						str=None			)							->    Dict:

									'''simple docstring'''







									if isinstance(lowercase ,      lowercase			):
															UpperCamelCase__         = [targets]
									try:
															UpperCamelCase__         = self.tokenizer.get_vocab()
									except Exception:
															UpperCamelCase__         = {}
									UpperCamelCase__         = []
									for target in targets:
															UpperCamelCase__         = vocab.get(lowercase ,      lowercase			)
															if id_ is None:
																					UpperCamelCase__         = 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
																					UpperCamelCase__         = 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__         = list(set(lowercase			)			)
									if len(lowercase			) == 0:
															raise ValueError("""At least one target must be provided when passed."""			)
									UpperCamelCase__         = np.array(lowercase			)
									return target_ids






			def 				A      (   self							:						Dict ,      lowercase							:						List[Any]=None ,      lowercase							:						Tuple=None			)							->    List[Any]:

									'''simple docstring'''







									UpperCamelCase__         = {}

									if targets is not None:
															UpperCamelCase__         = self.get_target_ids(lowercase ,      lowercase			)
															UpperCamelCase__         = target_ids

									if top_k is not None:
															UpperCamelCase__         = 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							:						Optional[int] ,      lowercase							:						str ,      *lowercase							:						List[Any] ,      **lowercase							:						int			)							->    Optional[Any]:

									'''simple docstring'''







									UpperCamelCase__         = super().__call__(lowercase ,      **lowercase			)
									if isinstance(lowercase ,      lowercase			) and len(lowercase			) == 1:
															return outputs[0]
									return outputs








'''simple docstring'''


import math







def 	__magic_name__( _A					):
						'''simple docstring'''





						assert isinstance(_A						,      _A					) and (
						    number >= 0
						), "'number' must been an int and positive"

						if 1 < number < 4:
												# 2 and 3 are primes
												return True
						elif number < 2 or not number % 2:
												# Negatives, 0, 1 and all even numbers are not primes
												return False

						UpperCamelCase__         = range(3						,      int(math.sqrt(_A					) + 1					)						,      2					)
						return not any(not number % i for i in odd_numbers					)







def 	__magic_name__( _A						,      _A=1						,      **_A					):
						'''simple docstring'''





						UpperCamelCase__         = factor * value
						UpperCamelCase__         = value

						while not is_prime(_A					):
												value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1

						if value == first_value_val:
												return next_prime(value + 1						,      **_A					)
						return value
