

'''simple docstring'''


import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
						from PIL import Image

						from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast



@require_vision
class 					lowercase						(  unittest.TestCase ):


							def 						_snake_case							(			self)							->				Union[str, Any]:
								UpperCAmelCase_		:      Tuple       	=					tempfile.mkdtemp()

								UpperCAmelCase_		:      Any       	=					BlipImageProcessor()
								UpperCAmelCase_		:      Dict       	=					BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-BertModel')

								UpperCAmelCase_		:      Optional[int]       	=					BlipProcessor(_snake_case    ,			_snake_case)

								processor.save_pretrained(self.tmpdirname)


							def 						_snake_case							(			self    ,			**_snake_case)							->				int:
								return AutoProcessor.from_pretrained(self.tmpdirname    ,			**_snake_case).tokenizer


							def 						_snake_case							(			self    ,			**_snake_case)							->				str:
								return AutoProcessor.from_pretrained(self.tmpdirname    ,			**_snake_case).image_processor


							def 						_snake_case							(			self)							->				List[Any]:
								shutil.rmtree(self.tmpdirname)


							def 						_snake_case							(			self)							->				Optional[int]:
								UpperCAmelCase_		:      str       	=					[np.random.randint(255    ,			size=(3, 30, 400)    ,			dtype=np.uinta)]

								UpperCAmelCase_		:      List[Any]       	=					[Image.fromarray(np.moveaxis(_snake_case    ,			0    ,			-1)) for x in image_inputs]

								return image_inputs


							def 						_snake_case							(			self)							->				Optional[Any]:
								UpperCAmelCase_		:      int       	=					BlipProcessor(tokenizer=self.get_tokenizer()    ,			image_processor=self.get_image_processor())
								processor.save_pretrained(self.tmpdirname)

								UpperCAmelCase_		:      Optional[int]       	=					self.get_tokenizer(bos_token='(BOS)'    ,			eos_token='(EOS)')
								UpperCAmelCase_		:      int       	=					self.get_image_processor(do_normalize=_snake_case    ,			padding_value=1.0)

								UpperCAmelCase_		:      int       	=					BlipProcessor.from_pretrained(
								    self.tmpdirname    ,			bos_token='(BOS)'    ,			eos_token='(EOS)'    ,			do_normalize=_snake_case    ,			padding_value=1.0)

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

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


							def 						_snake_case							(			self)							->				Optional[Any]:
								UpperCAmelCase_		:      List[Any]       	=					self.get_image_processor()
								UpperCAmelCase_		:      List[str]       	=					self.get_tokenizer()

								UpperCAmelCase_		:      Any       	=					BlipProcessor(tokenizer=_snake_case    ,			image_processor=_snake_case)

								UpperCAmelCase_		:      List[Any]       	=					self.prepare_image_inputs()

								UpperCAmelCase_		:      List[str]       	=					image_processor(_snake_case    ,			return_tensors='np')
								UpperCAmelCase_		:      Dict       	=					processor(images=_snake_case    ,			return_tensors='np')

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


							def 						_snake_case							(			self)							->				int:
								UpperCAmelCase_		:      int       	=					self.get_image_processor()
								UpperCAmelCase_		:      List[Any]       	=					self.get_tokenizer()

								UpperCAmelCase_		:      Dict       	=					BlipProcessor(tokenizer=_snake_case    ,			image_processor=_snake_case)

								UpperCAmelCase_		:      List[str]       	=					'lower newer'

								UpperCAmelCase_		:      List[Any]       	=					processor(text=_snake_case)

								UpperCAmelCase_		:      List[Any]       	=					tokenizer(_snake_case    ,			return_token_type_ids=_snake_case)

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


							def 						_snake_case							(			self)							->				Tuple:
								UpperCAmelCase_		:      List[str]       	=					self.get_image_processor()
								UpperCAmelCase_		:      Tuple       	=					self.get_tokenizer()

								UpperCAmelCase_		:      int       	=					BlipProcessor(tokenizer=_snake_case    ,			image_processor=_snake_case)

								UpperCAmelCase_		:      List[Any]       	=					'lower newer'
								UpperCAmelCase_		:      str       	=					self.prepare_image_inputs()

								UpperCAmelCase_		:      List[Any]       	=					processor(text=_snake_case    ,			images=_snake_case)

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

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


							def 						_snake_case							(			self)							->				str:
								UpperCAmelCase_		:      List[Any]       	=					self.get_image_processor()
								UpperCAmelCase_		:      List[str]       	=					self.get_tokenizer()

								UpperCAmelCase_		:      Any       	=					BlipProcessor(tokenizer=_snake_case    ,			image_processor=_snake_case)

								UpperCAmelCase_		:      Optional[Any]       	=					[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

								UpperCAmelCase_		:      Any       	=					processor.batch_decode(_snake_case)
								UpperCAmelCase_		:      Optional[int]       	=					tokenizer.batch_decode(_snake_case)

								self.assertListEqual(_snake_case    ,			_snake_case)





							def 						_snake_case							(			self)							->				Tuple:
								UpperCAmelCase_		:      List[str]       	=					self.get_image_processor()
								UpperCAmelCase_		:      Tuple       	=					self.get_tokenizer()

								UpperCAmelCase_		:      int       	=					BlipProcessor(tokenizer=_snake_case    ,			image_processor=_snake_case)

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

								UpperCAmelCase_		:      List[str]       	=					processor(text=_snake_case    ,			images=_snake_case)

								# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
								self.assertListEqual(list(inputs.keys())    ,			['pixel_values', 'input_ids', 'attention_mask'])









'''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__										= 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 					lowercase						(  a_ ):


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								if self.framework == "tf":
									UpperCAmelCase_		:      Dict       	=					tf.where(input_ids == self.tokenizer.mask_token_id).numpy()
								elif self.framework == "pt":
									UpperCAmelCase_		:      Any       	=					torch.nonzero(input_ids == self.tokenizer.mask_token_id    ,			as_tuple=_snake_case)
								else:
									raise ValueError('Unsupported framework')
								return masked_index


							def 						_snake_case							(			self    ,			_snake_case)							->				np.ndarray:
								UpperCAmelCase_		:      Optional[int]       	=					self.get_masked_index(_snake_case)
								UpperCAmelCase_		:      int       	=					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    ,			_snake_case)							->				int:
								if isinstance(_snake_case    ,			_snake_case):
									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(_snake_case)


							def 						_snake_case							(			self    ,			_snake_case    ,			_snake_case=None    ,			**_snake_case)							->				Dict[str, GenericTensor]:
								if return_tensors is None:
									UpperCAmelCase_		:      Optional[Any]       	=					self.framework
								UpperCAmelCase_		:      str       	=					self.tokenizer(_snake_case    ,			return_tensors=_snake_case)
								self.ensure_exactly_one_mask_token(_snake_case)
								return model_inputs


							def 						_snake_case							(			self    ,			_snake_case)							->				Optional[int]:
								UpperCAmelCase_		:      List[str]       	=					self.model(**_snake_case)
								UpperCAmelCase_		:      Optional[Any]       	=					model_inputs['input_ids']
								return model_outputs


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

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

									UpperCAmelCase_		:      Tuple       	=					outputs.numpy()

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

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

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

									UpperCAmelCase_	,    UpperCAmelCase_		:      Union[str, Any]       	=					probs.topk(_snake_case)

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

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


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


							def 						_snake_case							(			self    ,			_snake_case=None    ,			_snake_case=None)							->				Dict:
								UpperCAmelCase_		:      str       	=					{}

								if targets is not None:
									UpperCAmelCase_		:      Dict       	=					self.get_target_ids(_snake_case    ,			_snake_case)
									UpperCAmelCase_		:      Optional[int]       	=					target_ids

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






