




"""simple docstring"""







from __future__ import annotations

from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass




@dataclass
class    lowerCAmelCase__							:


				"""simple docstring"""





				__UpperCAmelCase			:  List[str]			   =   42
				__UpperCAmelCase			:  str			   =   42





class    lowerCAmelCase__							:


				"""simple docstring"""





				def __init__(  self       :						List[Any]     , lowercase__       :						Union[str, Any]    ):
						__lowercase					:		Union[str, Any]        =					[[] for _ in range(_a    )]
						__lowercase					:		int        =					size



				def __getitem__(  self       :						Tuple     , lowercase__       :						Union[str, Any]    ):
						return iter(self._graph[vertex]    )



				@property
				def    snake_case     (  self       :						Tuple    ):
						return self._size



				def    snake_case     (  self       :						str     , lowercase__       :						Tuple     , lowercase__       :						int     , lowercase__       :						Union[str, Any]    ):
						if weight not in (0, 1):
								raise ValueError("Edge weight must be either 0 or 1."    )

						if to_vertex < 0 or to_vertex >= self.size:
								raise ValueError("Vertex indexes must be in [0; size)."    )

						self._graph[from_vertex].append(Edge(_a     , _a    )    )



				def    snake_case     (  self       :						Optional[Any]     , lowercase__       :						List[Any]     , lowercase__       :						Union[str, Any]    ):
						__lowercase					:		Optional[int]        =					deque([start_vertex]    )
						__lowercase					:		Optional[int]        =					[None] * self.size
						__lowercase					:		Optional[Any]        =					0

						while queue:
								__lowercase					:		str        =					queue.popleft()
								__lowercase					:		List[Any]        =					distances[current_vertex]
								if current_distance is None:
										continue

								for edge in self[current_vertex]:
										__lowercase					:		Dict        =					current_distance + edge.weight
										__lowercase					:		Any        =					distances[edge.destination_vertex]
										if (
										    isinstance(_a     , _a    )
										    and new_distance >= dest_vertex_distance
										):
												continue
										__lowercase					:		Union[str, Any]        =					new_distance
										if edge.weight == 0:
												queue.appendleft(edge.destination_vertex    )
										else:
												queue.append(edge.destination_vertex    )

						if distances[finish_vertex] is None:
								raise ValueError("No path from start_vertex to finish_vertex."    )

						return distances[finish_vertex]


if __name__ == "__main__":
						import doctest

						doctest.testmod()






"""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				:     int					=				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__							):






				'''simple docstring'''





				def   _lowerCAmelCase							(			self						,					_a					):





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





				def   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   self.get_masked_index(_a					)
							lowerCamelCase      =   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   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							if isinstance(_a						,					_a					):
										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(_a					)





				def   _lowerCAmelCase							(			self						,					_a						,					_a=None						,					**_a					):





							"""simple docstring"""
							if return_tensors is None:
										lowerCamelCase      =   self.framework
							lowerCamelCase      =   self.tokenizer(_a						,					return_tensors=_a					)
							self.ensure_exactly_one_mask_token(_a					)
							return model_inputs





				def   _lowerCAmelCase							(			self						,					_a					):





							"""simple docstring"""
							lowerCamelCase      =   self.model(**_a					)
							lowerCamelCase      =   model_inputs["""input_ids"""]
							return model_outputs





				def   _lowerCAmelCase							(			self						,					_a						,					_a=5						,					_a=None					):





							"""simple docstring"""
							# Cap top_k if there are targets
							if target_ids is not None and target_ids.shape[0] < top_k:
										lowerCamelCase      =   target_ids.shape[0]
							lowerCamelCase      =   model_outputs["""input_ids"""][0]
							lowerCamelCase      =   model_outputs["""logits"""]

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

										lowerCamelCase      =   outputs.numpy()

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

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

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

										lowerCamelCase ,  lowerCamelCase      =   probs.topk(_a					)

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

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





				def   _lowerCAmelCase							(			self						,					_a						,					_a=None					):





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





				def   _lowerCAmelCase							(			self						,					_a=None						,					_a=None					):





							"""simple docstring"""
							lowerCamelCase      =   {}

							if targets is not None:
										lowerCamelCase      =   self.get_target_ids(_a						,					_a					)
										lowerCamelCase      =   target_ids

							if top_k is not None:
										lowerCamelCase      =   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						,					_a						,					*_a						,					**_a					):





							"""simple docstring"""
							lowerCamelCase      =   super().__call__(_a						,					**_a					)
							if isinstance(_a						,					_a					) and len(_a					) == 1:
										return outputs[0]
							return outputs



