

from __future__ import annotations

import unittest

from transformers import DistilBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import tensorflow as tf

				from transformers.models.distilbert.modeling_tf_distilbert import (
				    TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    TFDistilBertForMaskedLM,
				    TFDistilBertForMultipleChoice,
				    TFDistilBertForQuestionAnswering,
				    TFDistilBertForSequenceClassification,
				    TFDistilBertForTokenClassification,
				    TFDistilBertModel,
				)

class 						__UpperCamelCase    :




	def __init__(		self	:						Optional[Any]		,	lowerCAmelCase	:						str		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			parent
		UpperCAmelCase_       				=			13
		UpperCAmelCase_       				=			7
		UpperCAmelCase_       				=			True
		UpperCAmelCase_       				=			True
		UpperCAmelCase_       				=			False
		UpperCAmelCase_       				=			True
		UpperCAmelCase_       				=			99
		UpperCAmelCase_       				=			32
		UpperCAmelCase_       				=			2
		UpperCAmelCase_       				=			4
		UpperCAmelCase_       				=			37
		UpperCAmelCase_       				=			"gelu"
		UpperCAmelCase_       				=			0.1
		UpperCAmelCase_       				=			0.1
		UpperCAmelCase_       				=			512
		UpperCAmelCase_       				=			16
		UpperCAmelCase_       				=			2
		UpperCAmelCase_       				=			0.02
		UpperCAmelCase_       				=			3
		UpperCAmelCase_       				=			4
		UpperCAmelCase_       				=			None




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			ids_tensor([self.batch_size, self.seq_length]		,	self.vocab_size							)

		UpperCAmelCase_       				=			None
		if self.use_input_mask:
			UpperCAmelCase_       				=			random_attention_mask([self.batch_size, self.seq_length]							)

		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None
		if self.use_labels:
			UpperCAmelCase_       				=			ids_tensor([self.batch_size]		,	self.type_sequence_label_size							)
			UpperCAmelCase_       				=			ids_tensor([self.batch_size, self.seq_length]		,	self.num_labels							)
			UpperCAmelCase_       				=			ids_tensor([self.batch_size]		,	self.num_choices							)

		UpperCAmelCase_       				=			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		,	)

		return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels




	def       __A					(		self	:						List[Any]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertModel(config=lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}

		UpperCAmelCase_       				=			model(lowerCAmelCase							)

		UpperCAmelCase_       				=			[input_ids, input_mask]

		UpperCAmelCase_       				=			model(lowerCAmelCase							)

		self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, self.seq_length, self.hidden_size)							)




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertForMaskedLM(config=lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.seq_length, self.vocab_size)							)




	def       __A					(		self	:						Union[str, Any]		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						int		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertForQuestionAnswering(config=lowerCAmelCase							)
		UpperCAmelCase_       				=			{
		    "input_ids": input_ids,
		    "attention_mask": input_mask,
		}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.start_logits.shape		,	(self.batch_size, self.seq_length)							)
		self.parent.assertEqual(result.end_logits.shape		,	(self.batch_size, self.seq_length)							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						Union[str, Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.num_labels
		UpperCAmelCase_       				=			TFDistilBertForSequenceClassification(lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.num_labels)							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						Optional[int]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Any		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.num_choices
		UpperCAmelCase_       				=			TFDistilBertForMultipleChoice(lowerCAmelCase							)
		UpperCAmelCase_       				=			tf.tile(tf.expand_dims(lowerCAmelCase		,	1							)		,	(1, self.num_choices, 1)							)
		UpperCAmelCase_       				=			tf.tile(tf.expand_dims(lowerCAmelCase		,	1							)		,	(1, self.num_choices, 1)							)
		UpperCAmelCase_       				=			{
		    "input_ids": multiple_choice_inputs_ids,
		    "attention_mask": multiple_choice_input_mask,
		}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.num_choices)							)




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Dict		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						List[str]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.num_labels
		UpperCAmelCase_       				=			TFDistilBertForTokenClassification(lowerCAmelCase							)
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		UpperCAmelCase_       				=			model(lowerCAmelCase							)
		self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.seq_length, self.num_labels)							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.prepare_config_and_inputs()
		((UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_)				,   (UpperCAmelCase_))       				=			config_and_inputs
		UpperCAmelCase_       				=			{"input_ids": input_ids, "attention_mask": input_mask}
		return config, inputs_dict


@require_tf
class 						__UpperCamelCase    (					lowercase     ,     lowercase     ,     unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     (
	    (
	        TFDistilBertModel,
	        TFDistilBertForMaskedLM,
	        TFDistilBertForQuestionAnswering,
	        TFDistilBertForSequenceClassification,
	        TFDistilBertForTokenClassification,
	        TFDistilBertForMultipleChoice,
	    )
	    if is_tf_available()
	    else None
	)
	SCREAMING_SNAKE_CASE__    				=     (
	    {
	        'feature-extraction': TFDistilBertModel,
	        'fill-mask': TFDistilBertForMaskedLM,
	        'question-answering': TFDistilBertForQuestionAnswering,
	        'text-classification': TFDistilBertForSequenceClassification,
	        'token-classification': TFDistilBertForTokenClassification,
	        'zero-shot': TFDistilBertForSequenceClassification,
	    }
	    if is_tf_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE__    				=     False
	SCREAMING_SNAKE_CASE__    				=     False




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertModelTester(self							)
		UpperCAmelCase_       				=			ConfigTester(self		,	config_class=lowerCAmelCase		,	dim=37							)




	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		self.config_tester.run_common_tests()




	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_model(*lowerCAmelCase							)




	def       __A					(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_masked_lm(*lowerCAmelCase							)




	def       __A					(		self	:						Optional[int]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_question_answering(*lowerCAmelCase							)




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowerCAmelCase							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowerCAmelCase							)




	def       __A					(		self	:						Any							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_distilbert_for_token_classification(*lowerCAmelCase							)




	@slow
	def       __A					(		self	:						str							):


		'''simple docstring'''







		for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]							):
			UpperCAmelCase_       				=			TFDistilBertModel.from_pretrained(lowerCAmelCase							)
			self.assertIsNotNone(lowerCAmelCase							)


@require_tf
class 						__UpperCamelCase    (					unittest.TestCase						):




	@slow
	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			TFDistilBertModel.from_pretrained("distilbert-base-uncased"							)
		UpperCAmelCase_       				=			tf.constant([[0, 1, 2, 3, 4, 5]]							)
		UpperCAmelCase_       				=			model(lowerCAmelCase							)[0]

		UpperCAmelCase_       				=			[1, 6, 768]
		self.assertEqual(output.shape		,	lowerCAmelCase							)

		UpperCAmelCase_       				=			tf.constant(
		    [
		        [
		            [0.19_261_885, -0.13_732_955, 0.4_119_799],
		            [0.22_150_156, -0.07_422_661, 0.39_037_204],
		            [0.22_756_018, -0.0_896_414, 0.3_701_467],
		        ]
		    ]							)
		tf.debugging.assert_near(output[:, :3, :3]		,	lowerCAmelCase		,	atol=1e-4							)


import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


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

_a:    List[str] 							=			"""▁"""

_a:    Union[str, Any] 							=			{
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
}

_a:    Tuple 							=			{
    """vocab_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json"""
        ),
    },
    """spm_file""": {
        """facebook/s2t-small-librispeech-asr""": (
            """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model"""
        )
    },
}

_a:    Optional[int] 							=			{
    """facebook/s2t-small-librispeech-asr""": 1024,
}

_a:    List[Any] 							=			["""pt""", """fr""", """ru""", """nl""", """ro""", """it""", """es""", """de"""]

_a:    Tuple 							=			{"""mustc""": MUSTC_LANGS}

class 						__UpperCamelCase    (					lowercase						):
	SCREAMING_SNAKE_CASE__    				=     VOCAB_FILES_NAMES
	SCREAMING_SNAKE_CASE__    				=     PRETRAINED_VOCAB_FILES_MAP
	SCREAMING_SNAKE_CASE__    				=     MAX_MODEL_INPUT_SIZES
	SCREAMING_SNAKE_CASE__    				=     ['input_ids', 'attention_mask']

	SCREAMING_SNAKE_CASE__    				=     []




	def __init__(		self	:						Union[str, Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Tuple		,	lowerCAmelCase	:						Tuple="<s>"		,	lowerCAmelCase	:						Optional[int]="</s>"		,	lowerCAmelCase	:						Any="<pad>"		,	lowerCAmelCase	:						Union[str, Any]="<unk>"		,	lowerCAmelCase	:						Tuple=False		,	lowerCAmelCase	:						List[Any]=False		,	lowerCAmelCase	:						Optional[int]=None		,	lowerCAmelCase	:						List[str]=None		,	lowerCAmelCase	:						Optional[Dict[str, Any]] = None		,	**lowerCAmelCase	:						Any		,	):


		'''simple docstring'''







		UpperCAmelCase_       				=			{} if sp_model_kwargs is None else sp_model_kwargs

		super().__init__(
		    bos_token=lowerCAmelCase		,	eos_token=lowerCAmelCase		,	unk_token=lowerCAmelCase		,	pad_token=lowerCAmelCase		,	do_upper_case=lowerCAmelCase		,	do_lower_case=lowerCAmelCase		,	tgt_lang=lowerCAmelCase		,	lang_codes=lowerCAmelCase		,	sp_model_kwargs=self.sp_model_kwargs		,	**lowerCAmelCase		,	)
		UpperCAmelCase_       				=			do_upper_case
		UpperCAmelCase_       				=			do_lower_case

		UpperCAmelCase_       				=			load_json(lowerCAmelCase							)
		UpperCAmelCase_       				=			{v: k for k, v in self.encoder.items()}
		UpperCAmelCase_       				=			spm_file
		UpperCAmelCase_       				=			load_spm(lowerCAmelCase		,	self.sp_model_kwargs							)

		if lang_codes is not None:
			UpperCAmelCase_       				=			lang_codes
			UpperCAmelCase_       				=			LANGUAGES[lang_codes]
			UpperCAmelCase_       				=			[F"<lang:{lang}>" for lang in self.langs]
			UpperCAmelCase_       				=			{lang: self.sp_model.PieceToId(F"<lang:{lang}>"							) for lang in self.langs}

			UpperCAmelCase_       				=			self.lang_tokens
			UpperCAmelCase_       				=			tgt_lang if tgt_lang is not None else self.langs[0]

			self.set_tgt_lang_special_tokens(self._tgt_lang							)
		else:
			UpperCAmelCase_       				=			{}




	@property
	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		return len(self.encoder							)




	@property
	def       __A					(		self	:						Any							):


		'''simple docstring'''







		return self._tgt_lang




	@tgt_lang.setter
	def       __A					(		self	:						int		,	lowerCAmelCase	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			new_tgt_lang
		self.set_tgt_lang_special_tokens(lowerCAmelCase							)




	def       __A					(		self	:						List[Any]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.lang_code_to_id[tgt_lang]
		UpperCAmelCase_       				=			[lang_code_id]




	def       __A					(		self	:						List[str]		,	lowerCAmelCase	:						str							):


		'''simple docstring'''







		return self.sp_model.encode(lowerCAmelCase		,	out_type=lowerCAmelCase							)




	def       __A					(		self	:						str		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.encoder.get(lowerCAmelCase		,	self.encoder[self.unk_token]							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						int							):


		'''simple docstring'''







		return self.decoder.get(lowerCAmelCase		,	self.unk_token							)




	def       __A					(		self	:						Dict		,	lowerCAmelCase	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			[]
		UpperCAmelCase_       				=			""
		for token in tokens:
			# make sure that special tokens are not decoded using sentencepiece model
			if token in self.all_special_tokens:
				UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
				out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " "
				UpperCAmelCase_       				=			[]
			else:
				current_sub_tokens.append(lowerCAmelCase							)
		UpperCAmelCase_       				=			self.sp_model.decode(lowerCAmelCase							)
		out_string += decoded.upper() if self.do_upper_case else decoded
		return out_string.strip()




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						List[Any]		,	lowerCAmelCase	:						Optional[int]=None							):


		'''simple docstring'''







		if token_ids_a is None:
			return self.prefix_tokens + token_ids_a + [self.eos_token_id]
		# We don't expect to process pairs, but leave the pair logic for API consistency
		return self.prefix_tokens + token_ids_a + token_ids_a + [self.eos_token_id]




	def       __A					(		self	:						Any		,	lowerCAmelCase	:						List[int]		,	lowerCAmelCase	:						Optional[List[int]] = None		,	lowerCAmelCase	:						bool = False							):


		'''simple docstring'''







		if already_has_special_tokens:
			return super().get_special_tokens_mask(
			    token_ids_a=lowerCAmelCase		,	token_ids_a=lowerCAmelCase		,	already_has_special_tokens=lowerCAmelCase							)

		UpperCAmelCase_       				=			[1] * len(self.prefix_tokens							)
		UpperCAmelCase_       				=			[1]
		if token_ids_a is None:
			return prefix_ones + ([0] * len(lowerCAmelCase							)) + suffix_ones
		return prefix_ones + ([0] * len(lowerCAmelCase							)) + ([0] * len(lowerCAmelCase							)) + suffix_ones




	def       __A					(		self	:						Optional[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.encoder.copy()
		vocab.update(self.added_tokens_encoder							)
		return vocab




	def __getstate__(		self	:						Union[str, Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			self.__dict__.copy()
		UpperCAmelCase_       				=			None
		return state




	def __setstate__(		self	:						Tuple		,	lowerCAmelCase	:						Dict							):


		'''simple docstring'''







		UpperCAmelCase_       				=			d

		# for backward compatibility
		if not hasattr(self		,	"sp_model_kwargs"							):
			UpperCAmelCase_       				=			{}

		UpperCAmelCase_       				=			load_spm(self.spm_file		,	self.sp_model_kwargs							)




	def       __A					(		self	:						Optional[Any]		,	lowerCAmelCase	:						str		,	lowerCAmelCase	:						Optional[str] = None							):


		'''simple docstring'''







		UpperCAmelCase_       				=			Path(lowerCAmelCase							)
		assert save_dir.is_dir(), F"{save_directory} should be a directory"
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"]
		)
		UpperCAmelCase_       				=			save_dir / (
		    (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"]
		)

		save_json(self.encoder		,	lowerCAmelCase							)

		if os.path.abspath(self.spm_file							) != os.path.abspath(lowerCAmelCase							) and os.path.isfile(self.spm_file							):
			copyfile(self.spm_file		,	lowerCAmelCase							)
		elif not os.path.isfile(self.spm_file							):
			with open(lowerCAmelCase		,	"wb"							) as fi:
				UpperCAmelCase_       				=			self.sp_model.serialized_model_proto()
				fi.write(lowerCAmelCase							)

		return (str(lowerCAmelCase							), str(lowerCAmelCase							))



def       __lowerCAmelCase      (						A       ,     A    ):
	UpperCAmelCase_       				=			sentencepiece.SentencePieceProcessor(**A    )
	spm.Load(str(A    )    )
	return spm



def       __lowerCAmelCase      (						A    ):
	with open(A       ,     "r"    ) as f:
		return json.load(A    )




def       __lowerCAmelCase      (						A       ,     A    ):
	with open(A       ,     "w"    ) as f:
		json.dump(A       ,     A       ,     indent=2    )