


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


_lowercase      :      List[Any]				       =					logging.get_logger(__name__)






@add_end_docstrings(
    a__						,    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 	UpperCamelCase__(       a__	):




				def 					a__(		self      :			Any				,   lowerCAmelCase      :			str				)->					np.ndarray:

										"""simple docstring"""




										if self.framework == "tf":
																UpperCAmelCase					    =     tf.where(input_ids == self.tokenizer.mask_token_id				).numpy()
										elif self.framework == "pt":
																UpperCAmelCase					    =     torch.nonzero(input_ids == self.tokenizer.mask_token_id				,   as_tuple=lowerCAmelCase__				)
										else:
																raise ValueError('''Unsupported framework'''				)
										return masked_index




				def 					a__(		self      :			str				,   lowerCAmelCase      :			str				)->					np.ndarray:

										"""simple docstring"""




										UpperCAmelCase					    =     self.get_masked_index(lowerCAmelCase__				)
										UpperCAmelCase					    =     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      :			str				,   lowerCAmelCase      :			Dict				)->					Dict:

										"""simple docstring"""




										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 					a__(		self      :			Union[str, Any]				,   lowerCAmelCase      :			Dict				,   lowerCAmelCase      :			str=None				,   **lowerCAmelCase      :			List[Any]				)->					Dict[str, GenericTensor]:

										"""simple docstring"""




										if return_tensors is None:
																UpperCAmelCase					    =     self.framework
										UpperCAmelCase					    =     self.tokenizer(lowerCAmelCase__				,   return_tensors=lowerCAmelCase__				)
										self.ensure_exactly_one_mask_token(lowerCAmelCase__				)
										return model_inputs




				def 					a__(		self      :			Optional[int]				,   lowerCAmelCase      :			Union[str, Any]				)->					int:

										"""simple docstring"""




										UpperCAmelCase					    =     self.model(**lowerCAmelCase__				)
										UpperCAmelCase					    =     model_inputs["input_ids"]
										return model_outputs




				def 					a__(		self      :			str				,   lowerCAmelCase      :			str				,   lowerCAmelCase      :			Optional[int]=5				,   lowerCAmelCase      :			Any=None				)->					Union[str, Any]:

										"""simple docstring"""




										if target_ids is not None and target_ids.shape[0] < top_k:
																UpperCAmelCase					    =     target_ids.shape[0]
										UpperCAmelCase					    =     model_outputs["input_ids"][0]
										UpperCAmelCase					    =     model_outputs["logits"]

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

																UpperCAmelCase					    =     outputs.numpy()

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

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

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

																UpperCAmelCase					    =     probs.topk(lowerCAmelCase__				)

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

																						UpperCAmelCase					    =     p
																						# Filter padding out:
																						UpperCAmelCase					    =     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
																						UpperCAmelCase					    =     self.tokenizer.decode(lowerCAmelCase__				,   skip_special_tokens=lowerCAmelCase__				)
																						UpperCAmelCase					    =     {"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 					a__(		self      :			Optional[Any]				,   lowerCAmelCase      :			List[str]				,   lowerCAmelCase      :			Any=None				)->					Dict:

										"""simple docstring"""




										if isinstance(lowerCAmelCase__				,   lowerCAmelCase__				):
																UpperCAmelCase					    =     [targets]
										try:
																UpperCAmelCase					    =     self.tokenizer.get_vocab()
										except Exception:
																UpperCAmelCase					    =     {}
										UpperCAmelCase					    =     []
										for target in targets:
																UpperCAmelCase					    =     vocab.get(lowerCAmelCase__				,   lowerCAmelCase__				)
																if id_ is None:
																						UpperCAmelCase					    =     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
																						UpperCAmelCase					    =     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_				)
										UpperCAmelCase					    =     list(set(lowerCAmelCase__				)				)
										if len(lowerCAmelCase__				) == 0:
																raise ValueError('''At least one target must be provided when passed.'''				)
										UpperCAmelCase					    =     np.array(lowerCAmelCase__				)
										return target_ids




				def 					a__(		self      :			Optional[Any]				,   lowerCAmelCase      :			Union[str, Any]=None				,   lowerCAmelCase      :			int=None				)->					int:

										"""simple docstring"""




										UpperCAmelCase					    =     {}

										if targets is not None:
																UpperCAmelCase					    =     self.get_target_ids(lowerCAmelCase__				,   lowerCAmelCase__				)
																UpperCAmelCase					    =     target_ids

										if top_k is not None:
																UpperCAmelCase					    =     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				,   lowerCAmelCase      :			List[str]				,   *lowerCAmelCase      :			Optional[int]				,   **lowerCAmelCase      :			Optional[Any]				)->					str:

										"""simple docstring"""




										UpperCAmelCase					    =     super().__call__(lowerCAmelCase__				,   **lowerCAmelCase__				)
										if isinstance(lowerCAmelCase__				,   lowerCAmelCase__				) and len(lowerCAmelCase__				) == 1:
																return outputs[0]
										return outputs









'''simple docstring'''



import os
import tempfile
import unittest
import uuid
from pathlib import Path

from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision
from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText
from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available


if is_torch_available():
	import torch

if is_soundfile_availble():
	import soundfile as sf

if is_vision_available():
	from PIL import Image


def 				lowerCamelCase__				(	A       :      str=""					):




						'''simple docstring'''






						UpperCAmelCase					    =     tempfile.mkdtemp()
						return os.path.join(A				,       str(uuid.uuida()					) + suffix					)






@require_soundfile
@require_torch
class 	UpperCamelCase__(       unittest.TestCase	):




				def 					a__(		self      :			int				)->					int:

										"""simple docstring"""




										UpperCAmelCase					    =     torch.rand(12				,   dtype=torch.floataa				) - 0.5
										UpperCAmelCase					    =     AgentAudio(lowerCAmelCase				)
										UpperCAmelCase					    =     str(agent_type.to_string()				)

										# Ensure that the tensor and the agent_type's tensor are the same
										self.assertTrue(torch.allclose(lowerCAmelCase				,   agent_type.to_raw()				,   atol=1E-4				)				)

										del agent_type

										# Ensure the path remains even after the object deletion
										self.assertTrue(os.path.exists(lowerCAmelCase				)				)

										# Ensure that the file contains the same value as the original tensor
										UpperCAmelCase    ,    UpperCAmelCase					    =     sf.read(lowerCAmelCase				)
										self.assertTrue(torch.allclose(lowerCAmelCase				,   torch.tensor(lowerCAmelCase				)				,   atol=1E-4				)				)





				def 					a__(		self      :			Union[str, Any]				)->					Optional[Any]:

										"""simple docstring"""




										UpperCAmelCase					    =     torch.rand(12				,   dtype=torch.floataa				) - 0.5
										UpperCAmelCase					    =     get_new_path(suffix='''.wav'''				)
										sf.write(lowerCAmelCase				,   lowerCAmelCase				,   16000				)

										UpperCAmelCase					    =     AgentAudio(lowerCAmelCase				)

										self.assertTrue(torch.allclose(lowerCAmelCase				,   agent_type.to_raw()				,   atol=1E-4				)				)
										self.assertEqual(agent_type.to_string()				,   lowerCAmelCase				)







@require_vision
@require_torch
class 	UpperCamelCase__(       unittest.TestCase	):




				def 					a__(		self      :			List[Any]				)->					Any:

										"""simple docstring"""




										UpperCAmelCase					    =     torch.randint(0				,   256				,   (64, 64, 3)				)
										UpperCAmelCase					    =     AgentImage(lowerCAmelCase				)
										UpperCAmelCase					    =     str(agent_type.to_string()				)

										# Ensure that the tensor and the agent_type's tensor are the same
										self.assertTrue(torch.allclose(lowerCAmelCase				,   agent_type._tensor				,   atol=1E-4				)				)

										self.assertIsInstance(agent_type.to_raw()				,   Image.Image				)

										# Ensure the path remains even after the object deletion
										del agent_type
										self.assertTrue(os.path.exists(lowerCAmelCase				)				)




				def 					a__(		self      :			List[Any]				)->					List[Any]:

										"""simple docstring"""




										UpperCAmelCase					    =     Path(get_tests_dir('''fixtures/tests_samples/COCO'''				)				) / '''000000039769.png'''
										UpperCAmelCase					    =     Image.open(lowerCAmelCase				)
										UpperCAmelCase					    =     AgentImage(lowerCAmelCase				)

										self.assertTrue(path.samefile(agent_type.to_string()				)				)
										self.assertTrue(image == agent_type.to_raw()				)

										# Ensure the path remains even after the object deletion
										del agent_type
										self.assertTrue(os.path.exists(lowerCAmelCase				)				)





				def 					a__(		self      :			Optional[Any]				)->					List[str]:

										"""simple docstring"""




										UpperCAmelCase					    =     Path(get_tests_dir('''fixtures/tests_samples/COCO'''				)				) / '''000000039769.png'''
										UpperCAmelCase					    =     Image.open(lowerCAmelCase				)
										UpperCAmelCase					    =     AgentImage(lowerCAmelCase				)

										self.assertFalse(path.samefile(agent_type.to_string()				)				)
										self.assertTrue(image == agent_type.to_raw()				)

										# Ensure the path remains even after the object deletion
										del agent_type
										self.assertTrue(os.path.exists(lowerCAmelCase				)				)







class 	UpperCamelCase__(       unittest.TestCase	):




				def 					a__(		self      :			int				)->					Any:

										"""simple docstring"""




										UpperCAmelCase					    =     '''Hey!'''
										UpperCAmelCase					    =     AgentText(lowerCAmelCase				)

										self.assertEqual(lowerCAmelCase				,   agent_type.to_string()				)
										self.assertEqual(lowerCAmelCase				,   agent_type.to_raw()				)
										self.assertEqual(lowerCAmelCase				,   lowerCAmelCase				)





