






'''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:      List[Any]  				=				logging.get_logger(__name__)






@add_end_docstrings(
    _lowerCAmelCase,						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__     (	_lowerCAmelCase				):







	"""simple docstring"""



	def        snake_case__		(							self  ,      _lowercase       )						->  np.ndarray:







							if self.framework == "tf":
													lowercase_      :   Any        =			tf.where(input_ids == self.tokenizer.mask_token_id       ).numpy()
							elif self.framework == "pt":
													lowercase_      :   Optional[int]        =			torch.nonzero(input_ids == self.tokenizer.mask_token_id  ,      as_tuple=_lowerCAmelCase       )
							else:
													raise ValueError('Unsupported framework'       )
							return masked_index
	def        snake_case__		(							self  ,      _lowercase       )						->  np.ndarray:
							lowercase_      :   List[str]        =			self.get_masked_index(_lowerCAmelCase       )
							lowercase_      :   Tuple        =			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        snake_case__		(							self  ,      _lowercase       )						->  str:







							if isinstance(_lowerCAmelCase  ,      _lowerCAmelCase       ):
													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(_lowerCAmelCase       )
	def        snake_case__		(							self  ,      _lowercase  ,      _lowercase=None  ,      **_lowercase       )						->  Dict[str, GenericTensor]:







							if return_tensors is None:
													lowercase_      :   List[str]        =			self.framework
							lowercase_      :   List[Any]        =			self.tokenizer(_lowerCAmelCase  ,      return_tensors=_lowerCAmelCase       )
							self.ensure_exactly_one_mask_token(_lowerCAmelCase       )
							return model_inputs
	def        snake_case__		(							self  ,      _lowercase       )						->  Any:
							lowercase_      :   Dict        =			self.model(**_lowerCAmelCase       )
							lowercase_      :   int        =			model_inputs['input_ids']
							return model_outputs
	def        snake_case__		(							self  ,      _lowercase  ,      _lowercase=5  ,      _lowercase=None       )						->  Tuple:







							if target_ids is not None and target_ids.shape[0] < top_k:
													lowercase_      :   Any        =			target_ids.shape[0]
							lowercase_      :   List[str]        =			model_outputs['input_ids'][0]
							lowercase_      :   Tuple        =			model_outputs['logits']

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

													lowercase_      :   List[Any]        =			outputs.numpy()

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

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

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

													lowercase_  ,      lowercase_      :   Optional[int]        =			probs.topk(_lowerCAmelCase       )

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

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







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

							if targets is not None:
													lowercase_      :   str        =			self.get_target_ids(_lowerCAmelCase  ,      _lowerCAmelCase       )
													lowercase_      :   Any        =			target_ids

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








'''simple docstring'''

from pathlib import PurePosixPath
from typing import Optional

import fsspec
from fsspec import AbstractFileSystem
from huggingface_hub.hf_api import DatasetInfo

from ..utils.file_utils import get_authentication_headers_for_url
from ..utils.hub import hf_hub_url






class 							__magic_name__     (	UpperCAmelCase_				):







	"""simple docstring"""



	SCREAMING_SNAKE_CASE_					:      Union[str, Any]        =  ''
	SCREAMING_SNAKE_CASE_					:      Union[str, Any]        =  'hf-legacy'  # "hf://"" is reserved for hffs
	def __init__(							self  ,      _lowercase = None  ,      _lowercase = None  ,      **_lowercase  ,      )						->  Optional[Any]:
							super().__init__(self  ,      **_lowercase       )
							lowercase_      :   int        =			repo_info
							lowercase_      :   List[Any]        =			token
							lowercase_      :   Union[str, Any]        =			None
	def        lowerCamelCase__		(							self       )						->  Optional[Any]:
							if self.dir_cache is None:
													lowercase_      :   Optional[Any]        =			{}
													for hf_file in self.repo_info.siblings:
																			# TODO(QL): add sizes
																			lowercase_      :   str        =			{
																			    'name': hf_file.rfilename,
																			    'size': None,
																			    'type': 'file',
																			}
																			self.dir_cache.update(
																			    {
																			        str(_lowercase       ): {'name': str(_lowercase       ), 'size': None, 'type': 'directory'}
																			        for d in list(PurePosixPath(hf_file.rfilename       ).parents       )[:-1]
																			    }       )
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase = "rb"  ,      **_lowercase  ,      )						->  Dict:
							if not isinstance(self.repo_info  ,      _lowercase       ):
													raise NotImplementedError(f"Open is only implemented for dataset repositories, but got {self.repo_info}"       )
							lowercase_      :   Optional[int]        =			hf_hub_url(self.repo_info.id  ,      _lowercase  ,      revision=self.repo_info.sha       )
							return fsspec.open(
							    _lowercase  ,      mode=_lowercase  ,      headers=get_authentication_headers_for_url(_lowercase  ,      use_auth_token=self.token       )  ,      client_kwargs={'trust_env': True}  ,      ).open()
	def        lowerCamelCase__		(							self  ,      _lowercase  ,      **_lowercase       )						->  Tuple:
							self._get_dirs()
							lowercase_      :   str        =			self._strip_protocol(_lowercase       )
							if path in self.dir_cache:
													return self.dir_cache[path]
							else:
													raise FileNotFoundError(_lowercase       )







	def        lowerCamelCase__		(							self  ,      _lowercase  ,      _lowercase=False  ,      **_lowercase       )						->  List[str]:
							self._get_dirs()
							lowercase_      :   List[str]        =			PurePosixPath(path.strip('/'       )       )
							lowercase_      :   List[str]        =			{}
							for p, f in self.dir_cache.items():
													lowercase_      :   Tuple        =			PurePosixPath(p.strip('/'       )       )
													lowercase_      :   Optional[int]        =			p.parent
													if root == path:
																			lowercase_      :   List[str]        =			f
							lowercase_      :   List[str]        =			list(paths.values()       )
							if detail:
													return out
							else:
													return sorted(f['name'] for f in out       )
