

import gc
import unittest

from transformers import MODEL_FOR_MASKED_LM_MAPPING, TF_MODEL_FOR_MASKED_LM_MAPPING, FillMaskPipeline, pipeline
from transformers.pipelines import PipelineException
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_gpu,
    slow,
)

from .test_pipelines_common import ANY

@is_pipeline_test
class 						__UpperCamelCase    (					unittest.TestCase						):
	SCREAMING_SNAKE_CASE__    				=     MODEL_FOR_MASKED_LM_MAPPING
	SCREAMING_SNAKE_CASE__    				=     TF_MODEL_FOR_MASKED_LM_MAPPING




	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		super().tearDown()
		# clean-up as much as possible GPU memory occupied by PyTorch
		gc.collect()
		if is_torch_available():
			import torch

			torch.cuda.empty_cache()




	@require_tf
	def       __A					(		self	:						int							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(task="fill-mask"		,	model="sshleifer/tiny-distilroberta-base"		,	top_k=2		,	framework="tf"							)
		UpperCAmelCase_       				=			unmasker("My name is <mask>"							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        {"sequence": "My name is grouped", "score": 2.1e-05, "token": 38_015, "token_str": " grouped"},
		        {"sequence": "My name is accuser", "score": 2.1e-05, "token": 25_506, "token_str": " accuser"},
		    ]		,	)

		UpperCAmelCase_       				=			unmasker("The largest city in France is <mask>"							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        {
		            "sequence": "The largest city in France is grouped",
		            "score": 2.1e-05,
		            "token": 38_015,
		            "token_str": " grouped",
		        },
		        {
		            "sequence": "The largest city in France is accuser",
		            "score": 2.1e-05,
		            "token": 25_506,
		            "token_str": " accuser",
		        },
		    ]		,	)

		UpperCAmelCase_       				=			unmasker("My name is <mask>"		,	targets=[" Patrick", " Clara", " Teven"]		,	top_k=3							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        {"sequence": "My name is Clara", "score": 2e-05, "token": 13_606, "token_str": " Clara"},
		        {"sequence": "My name is Patrick", "score": 2e-05, "token": 3_499, "token_str": " Patrick"},
		        {"sequence": "My name is Te", "score": 1.9e-05, "token": 2_941, "token_str": " Te"},
		    ]		,	)




	@require_torch
	def       __A					(		self	:						str							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(task="fill-mask"		,	model="sshleifer/tiny-distilroberta-base"		,	top_k=2		,	framework="pt"							)

		UpperCAmelCase_       				=			unmasker("My name is <mask>"							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        {"sequence": "My name is Maul", "score": 2.2e-05, "token": 35_676, "token_str": " Maul"},
		        {"sequence": "My name isELS", "score": 2.2e-05, "token": 16_416, "token_str": "ELS"},
		    ]		,	)

		UpperCAmelCase_       				=			unmasker("The largest city in France is <mask>"							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        {
		            "sequence": "The largest city in France is Maul",
		            "score": 2.2e-05,
		            "token": 35_676,
		            "token_str": " Maul",
		        },
		        {"sequence": "The largest city in France isELS", "score": 2.2e-05, "token": 16_416, "token_str": "ELS"},
		    ]		,	)

		UpperCAmelCase_       				=			unmasker("My name is <mask>"		,	targets=[" Patrick", " Clara", " Teven"]		,	top_k=3							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        {"sequence": "My name is Patrick", "score": 2.1e-05, "token": 3_499, "token_str": " Patrick"},
		        {"sequence": "My name is Te", "score": 2e-05, "token": 2_941, "token_str": " Te"},
		        {"sequence": "My name is Clara", "score": 2e-05, "token": 13_606, "token_str": " Clara"},
		    ]		,	)

		UpperCAmelCase_       				=			unmasker("My name is <mask> <mask>"		,	top_k=2							)

		self.assertEqual(
		    nested_simplify(lowerCAmelCase		,	decimals=6							)		,	[
		        [
		            {
		                "score": 2.2e-05,
		                "token": 35_676,
		                "token_str": " Maul",
		                "sequence": "<s>My name is Maul<mask></s>",
		            },
		            {"score": 2.2e-05, "token": 16_416, "token_str": "ELS", "sequence": "<s>My name isELS<mask></s>"},
		        ],
		        [
		            {
		                "score": 2.2e-05,
		                "token": 35_676,
		                "token_str": " Maul",
		                "sequence": "<s>My name is<mask> Maul</s>",
		            },
		            {"score": 2.2e-05, "token": 16_416, "token_str": "ELS", "sequence": "<s>My name is<mask>ELS</s>"},
		        ],
		    ]		,	)




	@require_torch_gpu
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline("fill-mask"		,	model="hf-internal-testing/tiny-random-distilbert"		,	device=0		,	framework="pt"							)

		# convert model to fp16
		pipe.model.half()

		UpperCAmelCase_       				=			pipe("Paris is the [MASK] of France."							)
		# We actually don't care about the result, we just want to make sure
		# it works, meaning the float16 tensor got casted back to float32
		# for postprocessing.
		self.assertIsInstance(lowerCAmelCase		,	lowerCAmelCase							)




	@slow
	@require_torch
	def       __A					(		self	:						List[Any]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(task="fill-mask"		,	model="distilroberta-base"		,	top_k=2		,	framework="pt"							)
		self.run_large_test(lowerCAmelCase							)




	@slow
	@require_tf
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(task="fill-mask"		,	model="distilroberta-base"		,	top_k=2		,	framework="tf"							)
		self.run_large_test(lowerCAmelCase							)




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


		'''simple docstring'''







		UpperCAmelCase_       				=			unmasker("My name is <mask>"							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[
		        {"sequence": "My name is John", "score": 0.008, "token": 610, "token_str": " John"},
		        {"sequence": "My name is Chris", "score": 0.007, "token": 1_573, "token_str": " Chris"},
		    ]		,	)
		UpperCAmelCase_       				=			unmasker("The largest city in France is <mask>"							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[
		        {
		            "sequence": "The largest city in France is Paris",
		            "score": 0.251,
		            "token": 2_201,
		            "token_str": " Paris",
		        },
		        {
		            "sequence": "The largest city in France is Lyon",
		            "score": 0.214,
		            "token": 12_790,
		            "token_str": " Lyon",
		        },
		    ]		,	)

		UpperCAmelCase_       				=			unmasker("My name is <mask>"		,	targets=[" Patrick", " Clara", " Teven"]		,	top_k=3							)
		self.assertEqual(
		    nested_simplify(lowerCAmelCase							)		,	[
		        {"sequence": "My name is Patrick", "score": 0.005, "token": 3_499, "token_str": " Patrick"},
		        {"sequence": "My name is Clara", "score": 0.000, "token": 13_606, "token_str": " Clara"},
		        {"sequence": "My name is Te", "score": 0.000, "token": 2_941, "token_str": " Te"},
		    ]		,	)




	@require_torch
	def       __A					(		self	:						List[str]							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(task="fill-mask"		,	model="sshleifer/tiny-distilroberta-base"		,	framework="pt"							)
		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None
		self.run_pipeline_test(lowerCAmelCase		,	[]							)




	@require_tf
	def       __A					(		self	:						Tuple							):


		'''simple docstring'''







		UpperCAmelCase_       				=			pipeline(task="fill-mask"		,	model="sshleifer/tiny-distilroberta-base"		,	framework="tf"							)
		UpperCAmelCase_       				=			None
		UpperCAmelCase_       				=			None
		self.run_pipeline_test(lowerCAmelCase		,	[]							)




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


		'''simple docstring'''







		if tokenizer is None or tokenizer.mask_token_id is None:
			self.skipTest("The provided tokenizer has no mask token, (probably reformer or wav2vec2)"							)

		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)
		UpperCAmelCase_       				=			[
		    F"This is another {tokenizer.mask_token} test",
		]
		return fill_masker, examples




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


		'''simple docstring'''







		UpperCAmelCase_       				=			fill_masker.tokenizer
		UpperCAmelCase_       				=			fill_masker.model

		UpperCAmelCase_       				=			fill_masker(
		    F"This is a {tokenizer.mask_token}"		,	)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		    ]		,	)

		UpperCAmelCase_       				=			fill_masker([F"This is a {tokenizer.mask_token}"]							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		    ]		,	)

		UpperCAmelCase_       				=			fill_masker([F"This is a {tokenizer.mask_token}", F"Another {tokenizer.mask_token} great test."]							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        [
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        ],
		        [
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        ],
		    ]		,	)

		with self.assertRaises(lowerCAmelCase							):
			fill_masker([None]							)
		# No mask_token is not supported
		with self.assertRaises(lowerCAmelCase							):
			fill_masker("This is"							)

		self.run_test_top_k(lowerCAmelCase		,	lowerCAmelCase							)
		self.run_test_targets(lowerCAmelCase		,	lowerCAmelCase							)
		self.run_test_top_k_targets(lowerCAmelCase		,	lowerCAmelCase							)
		self.fill_mask_with_duplicate_targets_and_top_k(lowerCAmelCase		,	lowerCAmelCase							)
		self.fill_mask_with_multiple_masks(lowerCAmelCase		,	lowerCAmelCase							)




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


		'''simple docstring'''







		UpperCAmelCase_       				=			tokenizer.get_vocab()
		UpperCAmelCase_       				=			sorted(vocab.keys()							)[:2]
		# Pipeline argument
		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase		,	targets=lowerCAmelCase							)
		UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		    ]		,	)
		UpperCAmelCase_       				=			{vocab[el] for el in targets}
		self.assertEqual({el["token"] for el in outputs}		,	lowerCAmelCase							)
		UpperCAmelCase_       				=			[tokenizer.decode([x]							) for x in target_ids]
		self.assertEqual({el["token_str"] for el in outputs}		,	set(lowerCAmelCase							)							)

		# Call argument
		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)
		UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	targets=lowerCAmelCase							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		    ]		,	)
		UpperCAmelCase_       				=			{vocab[el] for el in targets}
		self.assertEqual({el["token"] for el in outputs}		,	lowerCAmelCase							)
		UpperCAmelCase_       				=			[tokenizer.decode([x]							) for x in target_ids]
		self.assertEqual({el["token_str"] for el in outputs}		,	set(lowerCAmelCase							)							)

		# Score equivalence
		UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	targets=lowerCAmelCase							)
		UpperCAmelCase_       				=			[top_mask["token_str"] for top_mask in outputs]
		UpperCAmelCase_       				=			[top_mask["score"] for top_mask in outputs]

		# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
		if set(lowerCAmelCase							) == set(lowerCAmelCase							):
			UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	targets=lowerCAmelCase							)
			UpperCAmelCase_       				=			[top_mask["score"] for top_mask in unmasked_targets]
			self.assertEqual(nested_simplify(lowerCAmelCase							)		,	nested_simplify(lowerCAmelCase							)							)

		# Raises with invalid
		with self.assertRaises(lowerCAmelCase							):
			UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	targets=[]							)
		# For some tokenizers, `""` is actually in the vocabulary and the expected error won't raised
		if "" not in tokenizer.get_vocab():
			with self.assertRaises(lowerCAmelCase							):
				UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	targets=[""]							)
			with self.assertRaises(lowerCAmelCase							):
				UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	targets=""							)




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


		'''simple docstring'''







		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase		,	top_k=2							)
		UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		    ]		,	)

		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)
		UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	top_k=2							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		    ]		,	)
		self.assertEqual(nested_simplify(lowerCAmelCase							)		,	nested_simplify(lowerCAmelCase							)							)




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


		'''simple docstring'''







		UpperCAmelCase_       				=			tokenizer.get_vocab()
		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)

		# top_k=2, ntargets=3
		UpperCAmelCase_       				=			sorted(vocab.keys()							)[:3]
		UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	top_k=2		,	targets=lowerCAmelCase							)

		# If we use the most probably targets, and filter differently, we should still
		# have the same results
		UpperCAmelCase_       				=			[el["token_str"] for el in sorted(lowerCAmelCase		,	key=lambda lowerCAmelCase							: x["score"]		,	reverse=lowerCAmelCase							)]
		# For some BPE tokenizers, `</w>` is removed during decoding, so `token_str` won't be the same as in `targets`.
		if set(lowerCAmelCase							).issubset(lowerCAmelCase							):
			UpperCAmelCase_       				=			fill_masker(F"This is a {tokenizer.mask_token}"		,	top_k=3		,	targets=lowerCAmelCase							)
			# They should yield exactly the same result
			self.assertEqual(nested_simplify(lowerCAmelCase							)		,	nested_simplify(lowerCAmelCase							)							)




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


		'''simple docstring'''







		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)
		UpperCAmelCase_       				=			tokenizer.get_vocab()
		# String duplicates + id duplicates
		UpperCAmelCase_       				=			sorted(vocab.keys()							)[:3]
		UpperCAmelCase_       				=			[targets[0], targets[1], targets[0], targets[2], targets[1]]
		UpperCAmelCase_       				=			fill_masker(F"My name is {tokenizer.mask_token}"		,	targets=lowerCAmelCase		,	top_k=10							)

		# The target list contains duplicates, so we can't output more
		# than them
		self.assertEqual(len(lowerCAmelCase							)		,	3							)




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


		'''simple docstring'''







		UpperCAmelCase_       				=			FillMaskPipeline(model=lowerCAmelCase		,	tokenizer=lowerCAmelCase							)

		UpperCAmelCase_       				=			fill_masker(
		    F"This is a {tokenizer.mask_token} {tokenizer.mask_token} {tokenizer.mask_token}"		,	top_k=2							)
		self.assertEqual(
		    lowerCAmelCase		,	[
		        [
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        ],
		        [
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        ],
		        [
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		            {"sequence": ANY(lowerCAmelCase							), "score": ANY(lowerCAmelCase							), "token": ANY(lowerCAmelCase							), "token_str": ANY(lowerCAmelCase							)},
		        ],
		    ]		,	)


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    )