



'''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						      =       logging.get_logger(__name__)

@add_end_docstrings(
    _UpperCamelCase      ,						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      __magic_name__						(   _UpperCamelCase       ):







							def 							__lowercase      (							self :	Optional[int]     ,_UpperCAmelCase :	GenericTensor		):
									if self.framework == "tf":
											_a					:				List[str]				=							tf.where(input_ids == self.tokenizer.mask_token_id		).numpy()
									elif self.framework == "pt":
											_a					:				Any				=							torch.nonzero(input_ids == self.tokenizer.mask_token_id     ,as_tuple=_UpperCAmelCase		)
									else:
											raise ValueError('Unsupported framework'		)
									return masked_index







							def 							__lowercase      (							self :	Tuple     ,_UpperCAmelCase :	GenericTensor		):
									_a					:				int				=							self.get_masked_index(_UpperCAmelCase		)
									_a					:				List[str]				=							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 :	int     ,_UpperCAmelCase :	GenericTensor		):
									if isinstance(_UpperCAmelCase     ,_UpperCAmelCase		):
											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(_UpperCAmelCase		)







							def 							__lowercase      (							self :	int     ,_UpperCAmelCase :	Optional[int]     ,_UpperCAmelCase :	str=None     ,**_UpperCAmelCase :	int		):
									if return_tensors is None:
											_a					:				Union[str, Any]				=							self.framework
									_a					:				Any				=							self.tokenizer(_UpperCAmelCase     ,return_tensors=_UpperCAmelCase		)
									self.ensure_exactly_one_mask_token(_UpperCAmelCase		)
									return model_inputs







							def 							__lowercase      (							self :	str     ,_UpperCAmelCase :	int		):
									_a					:				Optional[int]				=							self.model(**_UpperCAmelCase		)
									_a					:				Tuple				=							model_inputs['input_ids']
									return model_outputs







							def 							__lowercase      (							self :	Optional[int]     ,_UpperCAmelCase :	Any     ,_UpperCAmelCase :	str=5     ,_UpperCAmelCase :	Any=None		):
									# Cap top_k if there are targets
									if target_ids is not None and target_ids.shape[0] < top_k:
											_a					:				List[str]				=							target_ids.shape[0]
									_a					:				Dict				=							model_outputs['input_ids'][0]
									_a					:				Optional[int]				=							model_outputs['logits']

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

											_a					:				List[str]				=							outputs.numpy()

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

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

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

											_a	, _a					:				Union[str, Any]				=							probs.topk(_UpperCAmelCase		)

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

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







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







							def 							__lowercase      (							self :	Tuple     ,_UpperCAmelCase :	int=None     ,_UpperCAmelCase :	Dict=None		):
									_a					:				Dict				=							{}

									if targets is not None:
											_a					:				Dict				=							self.get_target_ids(_UpperCAmelCase     ,_UpperCAmelCase		)
											_a					:				Optional[int]				=							target_ids

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









'''simple docstring'''

from __future__ import annotations

from collections.abc import Iterator
from typing import Any

class      __magic_name__						:







							def __init__(							self :	Dict     ,_UpperCAmelCase :	Any		):
									_a					:				Any				=							data
									_a					:				Node | None				=							None

class      __magic_name__						:







							def __init__(							self :	Any		):
									_a					:				int				=							None
									_a					:				Optional[int]				=							None







							def __iter__(							self :	Optional[int]		):
									_a					:				List[Any]				=							self.head
									while self.head:
											yield node.data
											_a					:				str				=							node.next
											if node == self.head:
													break







							def __len__(							self :	Any		):
									return sum(1 for _ in self		)







							def __repr__(							self :	int		):
									return "->".join(str(_UpperCAmelCase		) for item in iter(self		)		)







							def 							__lowercase      (							self :	Optional[Any]     ,_UpperCAmelCase :	Any		):
									self.insert_nth(len(self		)     ,_UpperCAmelCase		)







							def 							__lowercase      (							self :	str     ,_UpperCAmelCase :	Any		):
									self.insert_nth(0     ,_UpperCAmelCase		)







							def 							__lowercase      (							self :	List[str]     ,_UpperCAmelCase :	int     ,_UpperCAmelCase :	Any		):
									if index < 0 or index > len(self		):
											raise IndexError('list index out of range.'		)
									_a					:				List[str]				=							Node(_UpperCAmelCase		)
									if self.head is None:
											_a					:				Tuple				=							new_node  # first node points itself
											_a					:				int				=							new_node
									elif index == 0:  # insert at head
											_a					:				Any				=							self.head
											_a					:				Tuple				=							new_node
									else:
											_a					:				Any				=							self.head
											for _ in range(index - 1		):
													_a					:				int				=							temp.next
											_a					:				Optional[int]				=							temp.next
											_a					:				int				=							new_node
											if index == len(self		) - 1:  # insert at tail
													_a					:				Optional[int]				=							new_node







							def 							__lowercase      (							self :	List[Any]		):
									return self.delete_nth(0		)







							def 							__lowercase      (							self :	Dict		):
									return self.delete_nth(len(self		) - 1		)







							def 							__lowercase      (							self :	Union[str, Any]     ,_UpperCAmelCase :	int = 0		):
									if not 0 <= index < len(self		):
											raise IndexError('list index out of range.'		)
									_a					:				Optional[int]				=							self.head
									if self.head == self.tail:  # just one node
											_a					:				Optional[int]				=							None
									elif index == 0:  # delete head node
											_a					:				Dict				=							self.tail.next.next
											_a					:				Dict				=							self.head.next
									else:
											_a					:				List[Any]				=							self.head
											for _ in range(index - 1		):
													_a					:				Union[str, Any]				=							temp.next
											_a					:				Optional[int]				=							temp.next
											_a					:				List[str]				=							temp.next.next
											if index == len(self		) - 1:  # delete at tail
													_a					:				int				=							temp
									return delete_node.data







							def 							__lowercase      (							self :	int		):
									return len(self		) == 0



def 					__lowerCamelCase					(				)      ->				None:
		_a					:				int				=							CircularLinkedList()
		assert len(lowerCAmelCase_  ) == 0
		assert circular_linked_list.is_empty() is True
		assert str(lowerCAmelCase_  ) == ""

		try:
				circular_linked_list.delete_front()
				raise AssertionError  # This should not happen
		except IndexError:
				assert True  # This should happen

		try:
				circular_linked_list.delete_tail()
				raise AssertionError  # This should not happen
		except IndexError:
				assert True  # This should happen

		try:
				circular_linked_list.delete_nth(-1  )
				raise AssertionError
		except IndexError:
				assert True

		try:
				circular_linked_list.delete_nth(0  )
				raise AssertionError
		except IndexError:
				assert True

		assert circular_linked_list.is_empty() is True
		for i in range(5  ):
				assert len(lowerCAmelCase_  ) == i
				circular_linked_list.insert_nth(lowerCAmelCase_						,      i + 1  )
		assert str(lowerCAmelCase_  ) == "->".join(str(lowerCAmelCase_  ) for i in range(1						,      6  )  )

		circular_linked_list.insert_tail(6  )
		assert str(lowerCAmelCase_  ) == "->".join(str(lowerCAmelCase_  ) for i in range(1						,      7  )  )
		circular_linked_list.insert_head(0  )
		assert str(lowerCAmelCase_  ) == "->".join(str(lowerCAmelCase_  ) for i in range(0						,      7  )  )

		assert circular_linked_list.delete_front() == 0
		assert circular_linked_list.delete_tail() == 6
		assert str(lowerCAmelCase_  ) == "->".join(str(lowerCAmelCase_  ) for i in range(1						,      6  )  )
		assert circular_linked_list.delete_nth(2  ) == 3

		circular_linked_list.insert_nth(2						,      3  )
		assert str(lowerCAmelCase_  ) == "->".join(str(lowerCAmelCase_  ) for i in range(1						,      6  )  )

		assert circular_linked_list.is_empty() is False


if __name__ == "__main__":
							import doctest

							doctest.testmod()




