



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


__snake_case							:   Dict      =    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 			A__   (  a__							):




	'''simple docstring'''





	def 							_SCREAMING_SNAKE_CASE   (     self:		str       ,			_SCREAMING_SNAKE_CASE:		Dict)				->       List[str]:

				"""simple docstring"""

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

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict       ,			_SCREAMING_SNAKE_CASE:		Any)				->       Optional[Any]:

				"""simple docstring"""

				__lowerCAmelCase      :  int												=       self.get_masked_index(_UpperCAmelCase)
				__lowerCAmelCase      :  Optional[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 							_SCREAMING_SNAKE_CASE   (     self:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Optional[int])				->       Any:

				"""simple docstring"""

				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 							_SCREAMING_SNAKE_CASE   (     self:		Dict       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		Any=None       ,			**_SCREAMING_SNAKE_CASE:		str)				->       Union[str, Any]:

				"""simple docstring"""

				if return_tensors is None:
							__lowerCAmelCase      :  Optional[int]												=       self.framework
				__lowerCAmelCase      :  List[Any]												=       self.tokenizer(_UpperCAmelCase       ,			return_tensors=_UpperCAmelCase)
				self.ensure_exactly_one_mask_token(_UpperCAmelCase)
				return model_inputs

	def 							_SCREAMING_SNAKE_CASE   (     self:		Union[str, Any]       ,			_SCREAMING_SNAKE_CASE:		Dict)				->       Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase      :  Tuple												=       self.model(**_UpperCAmelCase)
				__lowerCAmelCase      :  List[str]												=       model_inputs['input_ids']
				return model_outputs

	def 							_SCREAMING_SNAKE_CASE   (     self:		Dict       ,			_SCREAMING_SNAKE_CASE:		Dict       ,			_SCREAMING_SNAKE_CASE:		Union[str, Any]=5       ,			_SCREAMING_SNAKE_CASE:		Any=None)				->       Dict:

				"""simple docstring"""

				if target_ids is not None and target_ids.shape[0] < top_k:
							__lowerCAmelCase      :  int												=       target_ids.shape[0]
				__lowerCAmelCase      :  Optional[Any]												=       model_outputs['input_ids'][0]
				__lowerCAmelCase      :  List[Any]												=       model_outputs['logits']

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

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

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

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

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

							__lowerCAmelCase      :  List[Any]												=       probs.topk(_UpperCAmelCase)

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

										__lowerCAmelCase      :  List[Any]												=       p
										# Filter padding out:
										__lowerCAmelCase      :  Dict												=       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      :  Optional[int]												=       self.tokenizer.decode(_UpperCAmelCase       ,			skip_special_tokens=_UpperCAmelCase)
										__lowerCAmelCase      :  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 							_SCREAMING_SNAKE_CASE   (     self:		Dict       ,			_SCREAMING_SNAKE_CASE:		Optional[Any]       ,			_SCREAMING_SNAKE_CASE:		str=None)				->       Tuple:

				"""simple docstring"""

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

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

				"""simple docstring"""

				__lowerCAmelCase      :  List[str]												=       {}

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

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

				"""simple docstring"""

				__lowerCAmelCase      :  Any												=       super().__call__(_UpperCAmelCase       ,			**_UpperCAmelCase)
				if isinstance(_UpperCAmelCase       ,			_UpperCAmelCase) and len(_UpperCAmelCase) == 1:
							return outputs[0]
				return outputs






'''simple docstring'''




import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
  from PIL import Image

  from transformers import CLIPImageProcessor, CLIPProcessor


@require_vision
class  SCREAMING_SNAKE_CASE    (unittest.TestCase							):


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[Any]      =       tempfile.mkdtemp()

          # fmt: off
          __A						: Optional[int]      =       ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
          # fmt: on
          __A						: Tuple      =       dict(zip(_UpperCAmelCase						,	range(len(_UpperCAmelCase))))
          __A						: Any      =       ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
          __A						: List[str]      =       {'unk_token': '<unk>'}

          __A						: int      =       os.path.join(self.tmpdirname						,	VOCAB_FILES_NAMES['vocab_file'])
          __A						: Optional[int]      =       os.path.join(self.tmpdirname						,	VOCAB_FILES_NAMES['merges_file'])
          with open(self.vocab_file						,	'w'						,	encoding='utf-8') as fp:
               fp.write(json.dumps(_UpperCAmelCase) + '\n')
          with open(self.merges_file						,	'w'						,	encoding='utf-8') as fp:
               fp.write('\n'.join(_UpperCAmelCase))

          __A						: str      =       {
              'do_resize': True,
              'size': 20,
              'do_center_crop': True,
              'crop_size': 18,
              'do_normalize': True,
              'image_mean': [0.48145466, 0.4578275, 0.40821073],
              'image_std': [0.26862954, 0.26130258, 0.27577711],
          }
          __A						: Union[str, Any]      =       os.path.join(self.tmpdirname						,	_UpperCAmelCase)
          with open(self.image_processor_file						,	'w'						,	encoding='utf-8') as fp:
               json.dump(_UpperCAmelCase						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self						,	**_UpperCAmelCase):

          '''simple docstring'''






          return CLIPTokenizer.from_pretrained(self.tmpdirname						,	**_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self						,	**_UpperCAmelCase):

          '''simple docstring'''






          return CLIPTokenizerFast.from_pretrained(self.tmpdirname						,	**_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self						,	**_UpperCAmelCase):

          '''simple docstring'''






          return CLIPImageProcessor.from_pretrained(self.tmpdirname						,	**_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          shutil.rmtree(self.tmpdirname)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Tuple      =       [np.random.randint(255						,	size=(3, 30, 400)						,	dtype=np.uinta)]

          __A						: Optional[int]      =       [Image.fromarray(np.moveaxis(_UpperCAmelCase						,	0						,	-1)) for x in image_inputs]

          return image_inputs


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: str      =       self.get_tokenizer()
          __A						: int      =       self.get_rust_tokenizer()
          __A						: Any      =       self.get_image_processor()

          __A						: Union[str, Any]      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)
          processor_slow.save_pretrained(self.tmpdirname)
          __A						: Dict      =       CLIPProcessor.from_pretrained(self.tmpdirname						,	use_fast=_UpperCAmelCase)

          __A						: Union[str, Any]      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)
          processor_fast.save_pretrained(self.tmpdirname)
          __A						: Union[str, Any]      =       CLIPProcessor.from_pretrained(self.tmpdirname)

          self.assertEqual(processor_slow.tokenizer.get_vocab()						,	tokenizer_slow.get_vocab())
          self.assertEqual(processor_fast.tokenizer.get_vocab()						,	tokenizer_fast.get_vocab())
          self.assertEqual(tokenizer_slow.get_vocab()						,	tokenizer_fast.get_vocab())
          self.assertIsInstance(processor_slow.tokenizer						,	_UpperCAmelCase)
          self.assertIsInstance(processor_fast.tokenizer						,	_UpperCAmelCase)

          self.assertEqual(processor_slow.image_processor.to_json_string()						,	image_processor.to_json_string())
          self.assertEqual(processor_fast.image_processor.to_json_string()						,	image_processor.to_json_string())
          self.assertIsInstance(processor_slow.image_processor						,	_UpperCAmelCase)
          self.assertIsInstance(processor_fast.image_processor						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Dict      =       CLIPProcessor(tokenizer=self.get_tokenizer()						,	image_processor=self.get_image_processor())
          processor.save_pretrained(self.tmpdirname)

          __A						: Dict      =       self.get_tokenizer(bos_token='(BOS)'						,	eos_token='(EOS)')
          __A						: Any      =       self.get_image_processor(do_normalize=_UpperCAmelCase						,	padding_value=1.0)

          __A						: Tuple      =       CLIPProcessor.from_pretrained(
              self.tmpdirname						,	bos_token='(BOS)'						,	eos_token='(EOS)'						,	do_normalize=_UpperCAmelCase						,	padding_value=1.0)

          self.assertEqual(processor.tokenizer.get_vocab()						,	tokenizer_add_kwargs.get_vocab())
          self.assertIsInstance(processor.tokenizer						,	_UpperCAmelCase)

          self.assertEqual(processor.image_processor.to_json_string()						,	image_processor_add_kwargs.to_json_string())
          self.assertIsInstance(processor.image_processor						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[int]      =       self.get_image_processor()
          __A						: List[Any]      =       self.get_tokenizer()

          __A						: List[Any]      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)

          __A						: List[str]      =       self.prepare_image_inputs()

          __A						: Dict      =       image_processor(_UpperCAmelCase						,	return_tensors='np')
          __A						: str      =       processor(images=_UpperCAmelCase						,	return_tensors='np')

          for key in input_image_proc.keys():
               self.assertAlmostEqual(input_image_proc[key].sum()						,	input_processor[key].sum()						,	delta=1e-2)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: List[Any]      =       self.get_image_processor()
          __A						: List[str]      =       self.get_tokenizer()

          __A						: Optional[Any]      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)

          __A						: Dict      =       'lower newer'

          __A						: List[Any]      =       processor(text=_UpperCAmelCase)

          __A						: Optional[int]      =       tokenizer(_UpperCAmelCase)

          for key in encoded_tok.keys():
               self.assertListEqual(encoded_tok[key]						,	encoded_processor[key])


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Dict      =       self.get_image_processor()
          __A						: Optional[int]      =       self.get_tokenizer()

          __A						: Optional[Any]      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)

          __A						: int      =       'lower newer'
          __A						: Any      =       self.prepare_image_inputs()

          __A						: Tuple      =       processor(text=_UpperCAmelCase						,	images=_UpperCAmelCase)

          self.assertListEqual(list(inputs.keys())						,	['input_ids', 'attention_mask', 'pixel_values'])

          # test if it raises when no input is passed
          with pytest.raises(_UpperCAmelCase):
               processor()


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Any      =       self.get_image_processor()
          __A						: str      =       self.get_tokenizer()

          __A						: Optional[Any]      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)

          __A						: Dict      =       [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

          __A						: str      =       processor.batch_decode(_UpperCAmelCase)
          __A						: Optional[Any]      =       tokenizer.batch_decode(_UpperCAmelCase)

          self.assertListEqual(_UpperCAmelCase						,	_UpperCAmelCase)


     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          __A						: Optional[int]      =       self.get_image_processor()
          __A						: int      =       self.get_tokenizer()

          __A						: Any      =       CLIPProcessor(tokenizer=_UpperCAmelCase						,	image_processor=_UpperCAmelCase)

          __A						: Any      =       'lower newer'
          __A						: Any      =       self.prepare_image_inputs()

          __A						: Any      =       processor(text=_UpperCAmelCase						,	images=_UpperCAmelCase)

          self.assertListEqual(list(inputs.keys())						,	processor.model_input_names)