






"""simple docstring"""
import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
			import torch







class      UpperCamelCase_			(__A	):
	__magic_name__       =							'''char'''
	__magic_name__       =							'''bpe'''
	__magic_name__       =							'''wp'''





lowerCamelCase_							      = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)







class      UpperCamelCase_			(__A	):
	__magic_name__       =							['''image_processor''', '''char_tokenizer''']
	__magic_name__       =							'''ViTImageProcessor'''
	__magic_name__       =							'''MgpstrTokenizer'''





	def __init__( self   :					Optional[int]      ,      lowerCAmelCase_   :					Union[str, Any]=None      ,      lowerCAmelCase_   :					Any=None      ,      **lowerCAmelCase_   :					str		)		->     Optional[int]:
				UpperCAmelCase_	:					Optional[int]     	=   None
				if "feature_extractor" in kwargs:
							warnings.warn(
							    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
							    " instead."      ,      lowerCAmelCase_      ,      )
							UpperCAmelCase_	:					Union[str, Any]     	=   kwargs.pop("feature_extractor"		)

				UpperCAmelCase_	:					Dict     	=   image_processor if image_processor is not None else feature_extractor
				if image_processor is None:
							raise ValueError("You need to specify an `image_processor`."		)
				if tokenizer is None:
							raise ValueError("You need to specify a `tokenizer`."		)

				UpperCAmelCase_	:					List[str]     	=   tokenizer
				UpperCAmelCase_	:					List[str]     	=   AutoTokenizer.from_pretrained("gpt2"		)
				UpperCAmelCase_	:					List[str]     	=   AutoTokenizer.from_pretrained("bert-base-uncased"		)

				super().__init__(lowerCAmelCase_      ,      lowerCAmelCase_		)





	def __call__( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					Union[str, Any]=None      ,      lowerCAmelCase_   :					Union[str, Any]=None      ,      lowerCAmelCase_   :					List[Any]=None      ,      **lowerCAmelCase_   :					Tuple		)		->     List[Any]:
				if images is None and text is None:
							raise ValueError("You need to specify either an `images` or `text` input to process."		)

				if images is not None:
							UpperCAmelCase_	:					Tuple     	=   self.image_processor(lowerCAmelCase_      ,      return_tensors=lowerCAmelCase_      ,      **lowerCAmelCase_		)
				if text is not None:
							UpperCAmelCase_	:					str     	=   self.char_tokenizer(lowerCAmelCase_      ,      return_tensors=lowerCAmelCase_      ,      **lowerCAmelCase_		)

				if text is None:
							return inputs
				elif images is None:
							return encodings
				else:
							UpperCAmelCase_	:					List[str]     	=   encodings["input_ids"]
							return inputs





	def 	_SCREAMING_SNAKE_CASE ( self   :					str      ,      lowerCAmelCase_   :					Optional[Any]		)		->     str:
				UpperCAmelCase_	,      UpperCAmelCase_	,      UpperCAmelCase_	:					int     	=   sequences
				UpperCAmelCase_	:					Tuple     	=   char_preds.size(0		)

				UpperCAmelCase_	,      UpperCAmelCase_	:					int     	=   self._decode_helper(lowerCAmelCase_      ,      "char"		)
				UpperCAmelCase_	,      UpperCAmelCase_	:					str     	=   self._decode_helper(lowerCAmelCase_      ,      "bpe"		)
				UpperCAmelCase_	,      UpperCAmelCase_	:					Optional[int]     	=   self._decode_helper(lowerCAmelCase_      ,      "wp"		)

				UpperCAmelCase_	:					Dict     	=   []
				UpperCAmelCase_	:					Optional[Any]     	=   []
				for i in range(lowerCAmelCase_		):
							UpperCAmelCase_	:					Any     	=   [char_scores[i], bpe_scores[i], wp_scores[i]]
							UpperCAmelCase_	:					Union[str, Any]     	=   [char_strs[i], bpe_strs[i], wp_strs[i]]
							UpperCAmelCase_	:					Tuple     	=   scores.index(max(lowerCAmelCase_		)		)
							final_strs.append(strs[max_score_index]		)
							final_scores.append(scores[max_score_index]		)

				UpperCAmelCase_	:					Optional[Any]     	=   {}
				UpperCAmelCase_	:					Optional[Any]     	=   final_strs
				UpperCAmelCase_	:					Tuple     	=   final_scores
				UpperCAmelCase_	:					Optional[int]     	=   char_strs
				UpperCAmelCase_	:					int     	=   bpe_strs
				UpperCAmelCase_	:					Any     	=   wp_strs
				return out





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					Union[str, Any]      ,      lowerCAmelCase_   :					Optional[Any]		)		->     str:
				if format == DecodeType.CHARACTER:
							UpperCAmelCase_	:					Dict     	=   self.char_decode
							UpperCAmelCase_	:					Union[str, Any]     	=   1
							UpperCAmelCase_	:					Optional[Any]     	=   "[s]"
				elif format == DecodeType.BPE:
							UpperCAmelCase_	:					int     	=   self.bpe_decode
							UpperCAmelCase_	:					Optional[Any]     	=   2
							UpperCAmelCase_	:					Any     	=   "#"
				elif format == DecodeType.WORDPIECE:
							UpperCAmelCase_	:					Union[str, Any]     	=   self.wp_decode
							UpperCAmelCase_	:					Optional[int]     	=   102
							UpperCAmelCase_	:					Union[str, Any]     	=   "[SEP]"
				else:
							raise ValueError(f"""Format {format} is not supported."""		)

				UpperCAmelCase_	,      UpperCAmelCase_	:					Tuple     	=   [], []
				UpperCAmelCase_	:					int     	=   pred_logits.size(0		)
				UpperCAmelCase_	:					str     	=   pred_logits.size(1		)
				UpperCAmelCase_	,      UpperCAmelCase_	:					Union[str, Any]     	=   pred_logits.topk(1      ,      dim=-1      ,      largest=lowerCAmelCase_      ,      sorted=lowerCAmelCase_		)
				UpperCAmelCase_	:					Dict     	=   preds_index.view(-1      ,      lowerCAmelCase_		)[:, 1:]
				UpperCAmelCase_	:					Optional[Any]     	=   decoder(lowerCAmelCase_		)
				UpperCAmelCase_	,      UpperCAmelCase_	:					Optional[int]     	=   torch.nn.functional.softmax(lowerCAmelCase_      ,      dim=2		).max(dim=2		)
				UpperCAmelCase_	:					int     	=   preds_max_prob[:, 1:]

				for index in range(lowerCAmelCase_		):
							UpperCAmelCase_	:					Union[str, Any]     	=   preds_str[index].find(lowerCAmelCase_		)
							UpperCAmelCase_	:					Dict     	=   preds_str[index][:pred_eos]
							UpperCAmelCase_	:					Tuple     	=   preds_index[index].cpu().tolist()
							UpperCAmelCase_	:					Optional[int]     	=   pred_index.index(lowerCAmelCase_		) if eos_token in pred_index else -1
							UpperCAmelCase_	:					str     	=   preds_max_prob[index][: pred_eos_index + 1]
							UpperCAmelCase_	:					Dict     	=   pred_max_prob.cumprod(dim=0		)[-1] if pred_max_prob.nelement() != 0 else 0.0
							dec_strs.append(lowerCAmelCase_		)
							conf_scores.append(lowerCAmelCase_		)

				return dec_strs, conf_scores





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict      ,      lowerCAmelCase_   :					Any		)		->     List[str]:
				UpperCAmelCase_	:					List[Any]     	=   [seq.replace(" "      ,      ""		) for seq in self.char_tokenizer.batch_decode(lowerCAmelCase_		)]
				return decode_strs





	def 	_SCREAMING_SNAKE_CASE ( self   :					Any      ,      lowerCAmelCase_   :					Any		)		->     List[str]:
				return self.bpe_tokenizer.batch_decode(lowerCAmelCase_		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					Dict      ,      lowerCAmelCase_   :					Any		)		->     List[Any]:
				UpperCAmelCase_	:					Dict     	=   [seq.replace(" "      ,      ""		) for seq in self.wp_tokenizer.batch_decode(lowerCAmelCase_		)]
				return decode_strs











"""simple docstring"""
import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
			import jax.numpy as jnp

			from transformers.models.distilbert.modeling_flax_distilbert import (
			    FlaxDistilBertForMaskedLM,
			    FlaxDistilBertForMultipleChoice,
			    FlaxDistilBertForQuestionAnswering,
			    FlaxDistilBertForSequenceClassification,
			    FlaxDistilBertForTokenClassification,
			    FlaxDistilBertModel,
			)







class      UpperCamelCase_			(unittest.TestCase	):





	def __init__( self   :					int      ,      lowerCAmelCase_   :					Any      ,      lowerCAmelCase_   :					Union[str, Any]=13      ,      lowerCAmelCase_   :					Union[str, Any]=7      ,      lowerCAmelCase_   :					Optional[Any]=True      ,      lowerCAmelCase_   :					List[Any]=True      ,      lowerCAmelCase_   :					Any=True      ,      lowerCAmelCase_   :					Tuple=True      ,      lowerCAmelCase_   :					Tuple=99      ,      lowerCAmelCase_   :					str=32      ,      lowerCAmelCase_   :					Optional[int]=5      ,      lowerCAmelCase_   :					List[Any]=4      ,      lowerCAmelCase_   :					List[Any]=37      ,      lowerCAmelCase_   :					str="gelu"      ,      lowerCAmelCase_   :					Optional[Any]=0.1      ,      lowerCAmelCase_   :					Union[str, Any]=0.1      ,      lowerCAmelCase_   :					List[Any]=512      ,      lowerCAmelCase_   :					Dict=16      ,      lowerCAmelCase_   :					int=2      ,      lowerCAmelCase_   :					Union[str, Any]=0.0_2      ,      lowerCAmelCase_   :					Optional[Any]=4      ,      )		->     Tuple:
				UpperCAmelCase_	:					Optional[Any]     	=   parent
				UpperCAmelCase_	:					Tuple     	=   batch_size
				UpperCAmelCase_	:					str     	=   seq_length
				UpperCAmelCase_	:					Optional[int]     	=   is_training
				UpperCAmelCase_	:					Dict     	=   use_attention_mask
				UpperCAmelCase_	:					int     	=   use_token_type_ids
				UpperCAmelCase_	:					Tuple     	=   use_labels
				UpperCAmelCase_	:					Tuple     	=   vocab_size
				UpperCAmelCase_	:					Union[str, Any]     	=   hidden_size
				UpperCAmelCase_	:					int     	=   num_hidden_layers
				UpperCAmelCase_	:					List[str]     	=   num_attention_heads
				UpperCAmelCase_	:					str     	=   intermediate_size
				UpperCAmelCase_	:					List[str]     	=   hidden_act
				UpperCAmelCase_	:					Tuple     	=   hidden_dropout_prob
				UpperCAmelCase_	:					Optional[Any]     	=   attention_probs_dropout_prob
				UpperCAmelCase_	:					Optional[int]     	=   max_position_embeddings
				UpperCAmelCase_	:					Optional[Any]     	=   type_vocab_size
				UpperCAmelCase_	:					Dict     	=   type_sequence_label_size
				UpperCAmelCase_	:					List[Any]     	=   initializer_range
				UpperCAmelCase_	:					Any     	=   num_choices





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     str:
				UpperCAmelCase_	:					List[str]     	=   ids_tensor([self.batch_size, self.seq_length]      ,      self.vocab_size		)

				UpperCAmelCase_	:					Tuple     	=   None
				if self.use_attention_mask:
							UpperCAmelCase_	:					Dict     	=   random_attention_mask([self.batch_size, self.seq_length]		)

				UpperCAmelCase_	:					Any     	=   DistilBertConfig(
				    vocab_size=self.vocab_size      ,      dim=self.hidden_size      ,      n_layers=self.num_hidden_layers      ,      n_heads=self.num_attention_heads      ,      hidden_dim=self.intermediate_size      ,      hidden_act=self.hidden_act      ,      dropout=self.hidden_dropout_prob      ,      attention_dropout=self.attention_probs_dropout_prob      ,      max_position_embeddings=self.max_position_embeddings      ,      initializer_range=self.initializer_range      ,      tie_weights_=lowerCAmelCase_      ,      )

				return config, input_ids, attention_mask





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[Any]		)		->     Union[str, Any]:
				UpperCAmelCase_	:					Any     	=   self.prepare_config_and_inputs()
				UpperCAmelCase_	,      UpperCAmelCase_	,      UpperCAmelCase_	:					List[str]     	=   config_and_inputs
				UpperCAmelCase_	:					Optional[Any]     	=   {"input_ids": input_ids, "attention_mask": attention_mask}
				return config, inputs_dict







@require_flax
class      UpperCamelCase_			(__A							,		unittest.TestCase	):
	__magic_name__       =							(
	    (
	        FlaxDistilBertModel,
	        FlaxDistilBertForMaskedLM,
	        FlaxDistilBertForMultipleChoice,
	        FlaxDistilBertForQuestionAnswering,
	        FlaxDistilBertForSequenceClassification,
	        FlaxDistilBertForTokenClassification,
	        FlaxDistilBertForQuestionAnswering,
	    )
	    if is_flax_available()
	    else ()
	)





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[str]		)		->     Optional[Any]:
				UpperCAmelCase_	:					List[Any]     	=   FlaxDistilBertModelTester(self		)





	@slow
	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[Any]		)		->     List[str]:
				for model_class_name in self.all_model_classes:
							UpperCAmelCase_	:					str     	=   model_class_name.from_pretrained("distilbert-base-uncased"		)
							UpperCAmelCase_	:					List[str]     	=   model(np.ones((1, 1)		)		)
							self.assertIsNotNone(lowerCAmelCase_		)







@require_flax
class      UpperCamelCase_			(unittest.TestCase	):





	@slow
	def 	_SCREAMING_SNAKE_CASE ( self   :					str		)		->     Optional[int]:
				UpperCAmelCase_	:					Any     	=   FlaxDistilBertModel.from_pretrained("distilbert-base-uncased"		)
				UpperCAmelCase_	:					int     	=   np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]		)
				UpperCAmelCase_	:					List[str]     	=   np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]		)
				UpperCAmelCase_	:					Any     	=   model(lowerCAmelCase_      ,      attention_mask=lowerCAmelCase_		)[0]
				UpperCAmelCase_	:					Union[str, Any]     	=   (1, 11, 768)
				self.assertEqual(output.shape      ,      lowerCAmelCase_		)
				UpperCAmelCase_	:					Dict     	=   np.array([[[-0.1_6_3_9, 0.3_2_9_9, 0.1_6_4_8], [-0.1_7_4_6, 0.3_2_8_9, 0.1_7_1_0], [-0.1_8_8_4, 0.3_3_5_7, 0.1_8_1_0]]]		)

				self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]      ,      lowerCAmelCase_      ,      atol=1e-4		)		)



