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


UpperCamelCase_      	=	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					):




						def      __lowerCamelCase       (    self :       Tuple							,							UpperCamelCase_ :       GenericTensor      )     ->				np.ndarray:
													if self.framework == "tf":
																				SCREAMING_SNAKE_CASE__     :Any						    = tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
													elif self.framework == "pt":
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = torch.nonzero(input_ids == self.tokenizer.mask_token_id							,							as_tuple=UpperCamelCase_      )
													else:
																				raise ValueError('Unsupported framework'      )
													return masked_index




						def      __lowerCamelCase       (    self :       Optional[Any]							,							UpperCamelCase_ :       GenericTensor      )     ->				np.ndarray:
													SCREAMING_SNAKE_CASE__     :int						    = self.get_masked_index(UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = 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 :       List[Any]							,							UpperCamelCase_ :       GenericTensor      )     ->				List[Any]:
													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      __lowerCamelCase       (    self :       Dict							,							UpperCamelCase_ :       int							,							UpperCamelCase_ :       Optional[Any]=None							,							**UpperCamelCase_ :       List[Any]      )     ->				Dict[str, GenericTensor]:
													if return_tensors is None:
																				SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = self.framework
													SCREAMING_SNAKE_CASE__     :str						    = self.tokenizer(UpperCamelCase_							,							return_tensors=UpperCamelCase_      )
													self.ensure_exactly_one_mask_token(UpperCamelCase_      )
													return model_inputs




						def      __lowerCamelCase       (    self :       str							,							UpperCamelCase_ :       Any      )     ->				Tuple:
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = self.model(**UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :Dict						    = model_inputs['input_ids']
													return model_outputs




						def      __lowerCamelCase       (    self :       List[str]							,							UpperCamelCase_ :       Tuple							,							UpperCamelCase_ :       List[Any]=5							,							UpperCamelCase_ :       int=None      )     ->				str:
													# Cap top_k if there are targets
													if target_ids is not None and target_ids.shape[0] < top_k:
																				SCREAMING_SNAKE_CASE__     :List[str]						    = target_ids.shape[0]
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = model_outputs['input_ids'][0]
													SCREAMING_SNAKE_CASE__     :Any						    = model_outputs['logits']

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

																				SCREAMING_SNAKE_CASE__     :Optional[Any]						    = outputs.numpy()

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

																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = tf.math.top_k(UpperCamelCase_							,							k=UpperCamelCase_      )
																				SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Any						    = topk.values.numpy(), topk.indices.numpy()
													else:
																				SCREAMING_SNAKE_CASE__     :List[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

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

																				SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :str						    = probs.topk(UpperCamelCase_      )

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

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




						def      __lowerCamelCase       (    self :       Optional[Any]							,							UpperCamelCase_ :       Any=None							,							UpperCamelCase_ :       Optional[int]=None      )     ->				int:
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = {}

													if targets is not None:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.get_target_ids(UpperCamelCase_							,							UpperCamelCase_      )
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = target_ids

													if top_k is not None:
																				SCREAMING_SNAKE_CASE__     :int						    = 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 :       List[str]							,							UpperCamelCase_ :       List[str]							,							*UpperCamelCase_ :       Tuple							,							**UpperCamelCase_ :       Dict      )     ->				Tuple:
													SCREAMING_SNAKE_CASE__     :Any						    = super().__call__(UpperCamelCase_							,							**UpperCamelCase_      )
													if isinstance(UpperCamelCase_							,							UpperCamelCase_      ) and len(UpperCamelCase_      ) == 1:
																				return outputs[0]
													return outputs







'''simple docstring'''







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCamelCase_      	=	{
    '''configuration_x_clip''': [
        '''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''XCLIPConfig''',
        '''XCLIPTextConfig''',
        '''XCLIPVisionConfig''',
    ],
    '''processing_x_clip''': ['''XCLIPProcessor'''],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCamelCase_      	=	[
		    '''XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''XCLIPModel''',
		    '''XCLIPPreTrainedModel''',
		    '''XCLIPTextModel''',
		    '''XCLIPVisionModel''',
		]

if TYPE_CHECKING:
		from .configuration_x_clip import (
		    XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    XCLIPConfig,
		    XCLIPTextConfig,
		    XCLIPVisionConfig,
		)
		from .processing_x_clip import XCLIPProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_x_clip import (
				    XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
				    XCLIPModel,
				    XCLIPPreTrainedModel,
				    XCLIPTextModel,
				    XCLIPVisionModel,
				)

else:
		import sys

		UpperCamelCase_      	=	_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






