





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__   : Any         =       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 							__lowercase			(     SCREAMING_SNAKE_CASE__       ):






      def 			_a						(		self			,							lowercase_)     ->       np.ndarray:
       if self.framework == "tf":
        __snake_case         =			tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
       elif self.framework == "pt":
        __snake_case         =			torch.nonzero(input_ids == self.tokenizer.mask_token_id			,							as_tuple=_lowercase)
       else:
        raise ValueError('Unsupported framework')
       return masked_index






      def 			_a						(		self			,							lowercase_)     ->       np.ndarray:
       __snake_case         =			self.get_masked_index(_lowercase)
       __snake_case         =			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			,							lowercase_)     ->       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 			_a						(		self			,							lowercase_			,							lowercase_=None			,							**lowercase_)     ->       Dict[str, GenericTensor]:
       if return_tensors is None:
        __snake_case         =			self.framework
       __snake_case         =			self.tokenizer(_lowercase			,							return_tensors=_lowercase)
       self.ensure_exactly_one_mask_token(_lowercase)
       return model_inputs






      def 			_a						(		self			,							lowercase_)     ->       int:
       __snake_case         =			self.model(**_lowercase)
       __snake_case         =			model_inputs["input_ids"]
       return model_outputs






      def 			_a						(		self			,							lowercase_			,							lowercase_=5			,							lowercase_=None)     ->       Any:
       # Cap top_k if there are targets
       if target_ids is not None and target_ids.shape[0] < top_k:
        __snake_case         =			target_ids.shape[0]
       __snake_case         =			model_outputs["input_ids"][0]
       __snake_case         =			model_outputs["logits"]

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

        __snake_case         =			outputs.numpy()

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

        __snake_case         =			tf.math.top_k(_lowercase			,							k=_lowercase)
        __snake_case         =			topk.values.numpy(), topk.indices.numpy()
       else:
        __snake_case         =			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         =			outputs[0, masked_index, :]
        __snake_case         =			logits.softmax(dim=-1)
        if target_ids is not None:
         __snake_case         =			probs[..., target_ids]

        __snake_case         =			probs.topk(_lowercase)

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

         __snake_case         =			p
         # Filter padding out:
         __snake_case         =			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         =			self.tokenizer.decode(_lowercase			,							skip_special_tokens=_lowercase)
         __snake_case         =			{"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			,							lowercase_			,							lowercase_=None)     ->       List[str]:
       if isinstance(_lowercase			,							_lowercase):
        __snake_case         =			[targets]
       try:
        __snake_case         =			self.tokenizer.get_vocab()
       except Exception:
        __snake_case         =			{}
       __snake_case         =			[]
       for target in targets:
        __snake_case         =			vocab.get(_lowercase			,							_lowercase)
        if id_ is None:
         __snake_case         =			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         =			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(set(_lowercase))
       if len(_lowercase) == 0:
        raise ValueError('At least one target must be provided when passed.')
       __snake_case         =			np.array(_lowercase)
       return target_ids






      def 			_a						(		self			,							lowercase_=None			,							lowercase_=None)     ->       List[Any]:
       __snake_case         =			{}

       if targets is not None:
        __snake_case         =			self.get_target_ids(_lowercase			,							_lowercase)
        __snake_case         =			target_ids

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






"""simple docstring"""







from random import randint, random

def  __SCREAMING_SNAKE_CASE		(			lowerCamelCase_:							int     ,		lowerCamelCase_:							int     ,		lowerCamelCase_:							int     ,		lowerCamelCase_:							bool = False     ,		lowerCamelCase_:							bool = False     ,		lowerCamelCase_:							int = 5     ,		):
						"""simple docstring"""






						snake_case   :			str						    = [[-1] * number_of_cells]  # Create a highway without any car
						snake_case   :			str						    = 0
						snake_case   :			Any						    = max(lowerCamelCase_     ,		0 )
						while i < number_of_cells:
												snake_case   :			Optional[int]						    = (
												    randint(0     ,		lowerCamelCase_ ) if random_speed else initial_speed
												)  # Place the cars
												i += (
												    randint(1     ,		max_speed * 2 ) if random_frequency else frequency
												)  # Arbitrary number, may need tuning
						return highway

def  __SCREAMING_SNAKE_CASE		(			lowerCamelCase_:							list     ,		lowerCamelCase_:							int ):
						"""simple docstring"""






						snake_case   :			Any						    = 0
						snake_case   :			int						    = highway_now[car_index + 1 :]
						for cell in range(len(lowerCamelCase_ ) ):  # May need a better name for this
												if cells[cell] != -1:  # If the cell is not empty then
																		return distance  # we have the distance we wanted
												distance += 1
						# Here if the car is near the end of the highway
						return distance + get_distance(lowerCamelCase_     ,		-1 )

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






						snake_case   :			List[str]						    = len(lowerCamelCase_ )
						# Beforce calculations, the highway is empty
						snake_case   :			Dict						    = [-1] * number_of_cells

						for car_index in range(lowerCamelCase_ ):
												if highway_now[car_index] != -1:
																		# Add 1 to the current speed of the car and cap the speed
																		snake_case   :			Tuple						    = min(highway_now[car_index] + 1     ,		lowerCamelCase_ )
																		# Number of empty cell before the next car
																		snake_case   :			int						    = get_distance(lowerCamelCase_     ,		lowerCamelCase_ ) - 1
																		# We can't have the car causing an accident
																		snake_case   :			str						    = min(next_highway[car_index]     ,		lowerCamelCase_ )
																		if random() < probability:
																								# Randomly, a driver will slow down
																								snake_case   :			Optional[Any]						    = max(next_highway[car_index] - 1     ,		0 )
						return next_highway

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






						snake_case   :			Optional[Any]						    = len(highway[0] )

						for i in range(lowerCamelCase_ ):
												snake_case   :			Union[str, Any]						    = update(highway[i]     ,		lowerCamelCase_     ,		lowerCamelCase_ )
												snake_case   :			Optional[int]						    = [-1] * number_of_cells

												for car_index in range(lowerCamelCase_ ):
																		snake_case   :			List[Any]						    = next_speeds_calculated[car_index]
																		if speed != -1:
																								# Change the position based on the speed (with % to create the loop)
																								snake_case   :			Optional[Any]						    = (car_index + speed) % number_of_cells
																								# Commit the change of position
																								snake_case   :			Tuple						    = speed
												highway.append(lowerCamelCase_ )

						return highway


if __name__ == "__main__":
			import doctest

			doctest.testmod()



