

"""simple docstring"""


import copy
import os
import tempfile
from unittest import TestCase
from unittest.mock import patch

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import pytest

from datasets.arrow_writer import ArrowWriter, OptimizedTypedSequence, ParquetWriter, TypedSequence
from datasets.features import ArrayaD, ClassLabel, Features, Image, Value
from datasets.features.features import ArrayaDExtensionType, cast_to_python_objects
from datasets.keyhash import DuplicatedKeysError, InvalidKeyError

from .utils import require_pil





class     snake_case	(				__snake_case  ):

				def 							lowercase_     (	self							:				Optional[Any])->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			pa.array(TypedSequence([1, 2, 3]))
						self.assertEqual(arr.type     ,  pa.intaa())

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



						'''simple docstring'''


						with self.assertRaises(UpperCamelCase__):
								__lowerCAmelCase:       Dict          =			pa.array(TypedSequence([1, 2, 3])     ,  type=pa.intaa())

				def 							lowercase_     (	self							:				Optional[int])->   Any:



						'''simple docstring'''


						with self.assertRaises(UpperCamelCase__):
								__lowerCAmelCase:       str          =			pa.array(TypedSequence([1, 2, 3]     ,  try_type=Value("bool")     ,  type=Value("int64")))

				def 							lowercase_     (	self							:				Tuple)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			pa.array(TypedSequence([1, 2, 3]     ,  type=Value("int32")))
						self.assertEqual(arr.type     ,  pa.intaa())

				def 							lowercase_     (	self							:				Dict)->   Dict:



						'''simple docstring'''


						with self.assertRaises((TypeError, pa.lib.ArrowInvalid)):
								__lowerCAmelCase:       Optional[int]          =			pa.array(TypedSequence(["foo", "bar"]     ,  type=Value("int64")))

				def 							lowercase_     (	self							:				Optional[Any])->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       List[str]          =			pa.array(TypedSequence([1, 2, 3]     ,  try_type=Value("int32")))
						self.assertEqual(arr.type     ,  pa.intaa())

				def 							lowercase_     (	self							:				Any)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			pa.array(TypedSequence(["foo", "bar"]     ,  try_type=Value("int64")))
						self.assertEqual(arr.type     ,  pa.string())

				def 							lowercase_     (	self							:				Optional[int])->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			pa.array(TypedSequence([[[1, 2, 3]]]     ,  type=ArrayaD((1, 3)     ,  "int64")))
						self.assertEqual(arr.type     ,  ArrayaDExtensionType((1, 3)     ,  "int64"))

				def 							lowercase_     (	self							:				int)->   List[Any]:



						'''simple docstring'''


						with self.assertRaises((TypeError, pa.lib.ArrowInvalid)):
								__lowerCAmelCase:       Dict          =			pa.array(TypedSequence(["foo", "bar"]     ,  type=ArrayaD((1, 3)     ,  "int64")))

				def 							lowercase_     (	self							:				List[Any])->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Dict          =			pa.array(TypedSequence([[[1, 2, 3]]]     ,  try_type=ArrayaD((1, 3)     ,  "int64")))
						self.assertEqual(arr.type     ,  ArrayaDExtensionType((1, 3)     ,  "int64"))

				def 							lowercase_     (	self							:				int)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			pa.array(TypedSequence(["foo", "bar"]     ,  try_type=ArrayaD((1, 3)     ,  "int64")))
						self.assertEqual(arr.type     ,  pa.string())




				@require_pil
				def 							lowercase_     (	self							:				Any)->   List[Any]:



						'''simple docstring'''


						import PIL.Image

						__lowerCAmelCase:       List[Any]          =			PIL.Image.fromarray(np.arange(1_0     ,  dtype=np.uinta).reshape(2     ,  5))
						with patch(
						    "datasets.arrow_writer.cast_to_python_objects"     ,  side_effect=UpperCamelCase__) as mock_cast_to_python_objects:
								__lowerCAmelCase:       str          =			pa.array(TypedSequence([{"path": None, "bytes": B"image_bytes"}, pil_image]     ,  type=Image()))
								__lowerCAmelCase      , __lowerCAmelCase:       Any          =			mock_cast_to_python_objects.call_args_list[-1]
								self.assertIn("optimize_list_casting"     ,  UpperCamelCase__)
								self.assertFalse(kwargs["optimize_list_casting"])






def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Optional[int]:
		__lowerCAmelCase:       Tuple          =			pa.BufferReader(__SCREAMING_SNAKE_CASE ) if isinstance(__SCREAMING_SNAKE_CASE					, pa.Buffer ) else pa.memory_map(__SCREAMING_SNAKE_CASE )
		__lowerCAmelCase:       str          =			pa.ipc.open_stream(__SCREAMING_SNAKE_CASE )
		__lowerCAmelCase:       pa.Table          =			f.read_all()
		assert len(pa_table.to_batches() ) == expected_num_chunks
		assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
		del pa_table






@pytest.mark.parametrize("writer_batch_size"					, [None, 1, 1_0] )
@pytest.mark.parametrize(
    "fields"					, [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Any:
		__lowerCAmelCase:       Tuple          =			pa.BufferOutputStream()
		__lowerCAmelCase:       List[str]          =			pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None
		with ArrowWriter(stream=__SCREAMING_SNAKE_CASE					, schema=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write({"col_1": "foo", "col_2": 1} )
				writer.write({"col_1": "bar", "col_2": 2} )
				__lowerCAmelCase      , __lowerCAmelCase:       Union[str, Any]          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		if not fields:
				__lowerCAmelCase:       Dict          =			{"col_1": pa.string(), "col_2": pa.intaa()}
		assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE					, metadata=writer._schema.metadata )
		_check_output(output.getvalue()					, expected_num_chunks=num_examples if writer_batch_size == 1 else 1 )






def     a__    (    )	->	Any:
		__lowerCAmelCase:       List[Any]          =			pa.BufferOutputStream()
		__lowerCAmelCase:       str          =			Features({"labels": ClassLabel(names=["neg", "pos"] )} )
		with ArrowWriter(stream=__SCREAMING_SNAKE_CASE					, features=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write({"labels": 0} )
				writer.write({"labels": 1} )
				__lowerCAmelCase      , __lowerCAmelCase:       Optional[Any]          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		assert writer._schema == features.arrow_schema
		assert writer._schema.metadata == features.arrow_schema.metadata
		__lowerCAmelCase:       Union[str, Any]          =			pa.BufferReader(output.getvalue() )
		__lowerCAmelCase:       Tuple          =			pa.ipc.open_stream(__SCREAMING_SNAKE_CASE )
		__lowerCAmelCase:       pa.Table          =			f.read_all()
		__lowerCAmelCase:       str          =			pa_table.schema
		assert pa_table.num_rows == 2
		assert schema == features.arrow_schema
		assert schema.metadata == features.arrow_schema.metadata
		assert features == Features.from_arrow_schema(__SCREAMING_SNAKE_CASE )






@pytest.mark.parametrize("writer_batch_size"					, [None, 1, 1_0] )
def     a__    (    __SCREAMING_SNAKE_CASE )	->	Optional[Any]:
		__lowerCAmelCase:       Any          =			pa.BufferOutputStream()
		with ArrowWriter(
		    stream=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE					, hash_salt="split_name"					, check_duplicates=__SCREAMING_SNAKE_CASE					, ) as writer:
				with pytest.raises(__SCREAMING_SNAKE_CASE ):
						writer.write({"col_1": "foo", "col_2": 1}					, key=[1, 2] )
						__lowerCAmelCase      , __lowerCAmelCase:       Dict          =			writer.finalize()






@pytest.mark.parametrize("writer_batch_size"					, [None, 2, 1_0] )
def     a__    (    __SCREAMING_SNAKE_CASE )	->	List[Any]:
		__lowerCAmelCase:       Optional[int]          =			pa.BufferOutputStream()
		with ArrowWriter(
		    stream=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE					, hash_salt="split_name"					, check_duplicates=__SCREAMING_SNAKE_CASE					, ) as writer:
				with pytest.raises(__SCREAMING_SNAKE_CASE ):
						writer.write({"col_1": "foo", "col_2": 1}					, key=1_0 )
						writer.write({"col_1": "bar", "col_2": 2}					, key=1_0 )
						__lowerCAmelCase      , __lowerCAmelCase:       Optional[int]          =			writer.finalize()






@pytest.mark.parametrize("writer_batch_size"					, [None, 2, 1_0] )
def     a__    (    __SCREAMING_SNAKE_CASE )	->	Dict:
		__lowerCAmelCase:       Optional[Any]          =			pa.BufferOutputStream()
		with ArrowWriter(
		    stream=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE					, hash_salt="split_name"					, check_duplicates=__SCREAMING_SNAKE_CASE					, ) as writer:
				writer.write({"col_1": "foo", "col_2": 1}					, key=1 )
				writer.write({"col_1": "bar", "col_2": 2}					, key=2 )
				__lowerCAmelCase      , __lowerCAmelCase:       List[Any]          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		_check_output(output.getvalue()					, expected_num_chunks=num_examples if writer_batch_size == 1 else 1 )






@pytest.mark.parametrize("writer_batch_size"					, [None, 1, 1_0] )
@pytest.mark.parametrize(
    "fields"					, [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	str:
		__lowerCAmelCase:       str          =			pa.BufferOutputStream()
		__lowerCAmelCase:       Union[str, Any]          =			pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None
		with ArrowWriter(stream=__SCREAMING_SNAKE_CASE					, schema=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} )
				writer.write_batch({"col_1": [], "col_2": []} )
				__lowerCAmelCase      , __lowerCAmelCase:       Optional[int]          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		if not fields:
				__lowerCAmelCase:       Optional[int]          =			{"col_1": pa.string(), "col_2": pa.intaa()}
		assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE					, metadata=writer._schema.metadata )
		_check_output(output.getvalue()					, expected_num_chunks=num_examples if writer_batch_size == 1 else 1 )






@pytest.mark.parametrize("writer_batch_size"					, [None, 1, 1_0] )
@pytest.mark.parametrize(
    "fields"					, [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	int:
		__lowerCAmelCase:       Union[str, Any]          =			pa.BufferOutputStream()
		__lowerCAmelCase:       Any          =			pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None
		with ArrowWriter(stream=__SCREAMING_SNAKE_CASE					, schema=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write_table(pa.Table.from_pydict({"col_1": ["foo", "bar"], "col_2": [1, 2]} ) )
				__lowerCAmelCase      , __lowerCAmelCase:       Optional[Any]          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		if not fields:
				__lowerCAmelCase:       Any          =			{"col_1": pa.string(), "col_2": pa.intaa()}
		assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE					, metadata=writer._schema.metadata )
		_check_output(output.getvalue()					, expected_num_chunks=num_examples if writer_batch_size == 1 else 1 )






@pytest.mark.parametrize("writer_batch_size"					, [None, 1, 1_0] )
@pytest.mark.parametrize(
    "fields"					, [None, {"col_1": pa.string(), "col_2": pa.intaa()}, {"col_1": pa.string(), "col_2": pa.intaa()}] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Optional[int]:
		__lowerCAmelCase:       Union[str, Any]          =			pa.BufferOutputStream()
		__lowerCAmelCase:       Any          =			pa.schema(__SCREAMING_SNAKE_CASE ) if fields else None
		with ArrowWriter(stream=__SCREAMING_SNAKE_CASE					, schema=__SCREAMING_SNAKE_CASE					, writer_batch_size=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write_row(pa.Table.from_pydict({"col_1": ["foo"], "col_2": [1]} ) )
				writer.write_row(pa.Table.from_pydict({"col_1": ["bar"], "col_2": [2]} ) )
				__lowerCAmelCase      , __lowerCAmelCase:       Dict          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		if not fields:
				__lowerCAmelCase:       Union[str, Any]          =			{"col_1": pa.string(), "col_2": pa.intaa()}
		assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE					, metadata=writer._schema.metadata )
		_check_output(output.getvalue()					, expected_num_chunks=num_examples if writer_batch_size == 1 else 1 )






def     a__    (    )	->	Union[str, Any]:
		with tempfile.TemporaryDirectory() as tmp_dir:
				__lowerCAmelCase:       Tuple          =			{"col_1": pa.string(), "col_2": pa.intaa()}
				__lowerCAmelCase:       List[Any]          =			os.path.join(__SCREAMING_SNAKE_CASE					, "test.arrow" )
				with ArrowWriter(path=__SCREAMING_SNAKE_CASE					, schema=pa.schema(__SCREAMING_SNAKE_CASE ) ) as writer:
						writer.write_batch({"col_1": ["foo", "bar"], "col_2": [1, 2]} )
						__lowerCAmelCase      , __lowerCAmelCase:       Tuple          =			writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				assert writer._schema == pa.schema(__SCREAMING_SNAKE_CASE					, metadata=writer._schema.metadata )
				_check_output(__SCREAMING_SNAKE_CASE					, 1 )






def     a__    (    __SCREAMING_SNAKE_CASE )	->	List[str]:
		if pa.types.is_list(__SCREAMING_SNAKE_CASE ):
				return get_base_dtype(arr_type.value_type )
		else:
				return arr_type






def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Union[str, Any]:
		if isinstance(lst[0]					, __SCREAMING_SNAKE_CASE ):
				change_first_primitive_element_in_list(lst[0]					, __SCREAMING_SNAKE_CASE )
		else:
				__lowerCAmelCase:       str          =			value






@pytest.mark.parametrize("optimized_int_type, expected_dtype"					, [(None, pa.intaa()), (Value("int32" ), pa.intaa())] )
@pytest.mark.parametrize("sequence"					, [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Optional[Any]:
		__lowerCAmelCase:       Any          =			pa.array(TypedSequence(__SCREAMING_SNAKE_CASE					, optimized_int_type=__SCREAMING_SNAKE_CASE ) )
		assert get_base_dtype(arr.type ) == expected_dtype






@pytest.mark.parametrize(
    "col, expected_dtype"					, [
        ("attention_mask", pa.inta()),
        ("special_tokens_mask", pa.inta()),
        ("token_type_ids", pa.inta()),
        ("input_ids", pa.intaa()),
        ("other", pa.intaa()),
    ]					, )
@pytest.mark.parametrize("sequence"					, [[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Tuple:
		# in range
		__lowerCAmelCase:       Optional[Any]          =			pa.array(OptimizedTypedSequence(__SCREAMING_SNAKE_CASE					, col=__SCREAMING_SNAKE_CASE ) )
		assert get_base_dtype(arr.type ) == expected_dtype

		# not in range
		if col != "other":
				# avoids errors due to in-place modifications
				__lowerCAmelCase:       Tuple          =			copy.deepcopy(__SCREAMING_SNAKE_CASE )
				__lowerCAmelCase:       str          =			np.iinfo(expected_dtype.to_pandas_dtype() ).max + 1
				change_first_primitive_element_in_list(__SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )
				__lowerCAmelCase:       Tuple          =			pa.array(OptimizedTypedSequence(__SCREAMING_SNAKE_CASE					, col=__SCREAMING_SNAKE_CASE ) )
				assert get_base_dtype(arr.type ) == pa.intaa()






@pytest.mark.parametrize("raise_exception"					, [False, True] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Union[str, Any]:
		__lowerCAmelCase:       Union[str, Any]          =			str(tmp_path / "dataset-train.arrow" )
		try:
				with ArrowWriter(path=__SCREAMING_SNAKE_CASE ) as writer:
						if raise_exception:
								raise pa.lib.ArrowInvalid()
						else:
								writer.stream.close()
		except pa.lib.ArrowInvalid:
				pass
		finally:
				assert writer.stream.closed






def     a__    (    __SCREAMING_SNAKE_CASE )	->	Any:
		__lowerCAmelCase:       Tuple          =			"mock://dataset-train.arrow"
		with ArrowWriter(path=__SCREAMING_SNAKE_CASE					, storage_options=mockfs.storage_options ) as writer:
				assert isinstance(writer._fs					, type(__SCREAMING_SNAKE_CASE ) )
				assert writer._fs.storage_options == mockfs.storage_options
				writer.write({"col_1": "foo", "col_2": 1} )
				writer.write({"col_1": "bar", "col_2": 2} )
				__lowerCAmelCase      , __lowerCAmelCase:       Any          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		assert mockfs.exists(__SCREAMING_SNAKE_CASE )






def     a__    (    )	->	Optional[Any]:
		__lowerCAmelCase:       Any          =			pa.BufferOutputStream()
		with ParquetWriter(stream=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write({"col_1": "foo", "col_2": 1} )
				writer.write({"col_1": "bar", "col_2": 2} )
				__lowerCAmelCase      , __lowerCAmelCase:       List[Any]          =			writer.finalize()
		assert num_examples == 2
		assert num_bytes > 0
		__lowerCAmelCase:       Dict          =			pa.BufferReader(output.getvalue() )
		__lowerCAmelCase:       pa.Table          =			pq.read_table(__SCREAMING_SNAKE_CASE )
		assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}






@require_pil
@pytest.mark.parametrize("embed_local_files"					, [False, True] )
def     a__    (    __SCREAMING_SNAKE_CASE					, __SCREAMING_SNAKE_CASE )	->	Optional[Any]:
		import PIL.Image

		__lowerCAmelCase:       int          =			str(tmp_path / "test_image_rgb.jpg" )
		PIL.Image.fromarray(np.zeros((5, 5)					, dtype=np.uinta ) ).save(__SCREAMING_SNAKE_CASE					, format="png" )
		__lowerCAmelCase:       Dict          =			pa.BufferOutputStream()
		with ParquetWriter(
		    stream=__SCREAMING_SNAKE_CASE					, features=Features({"image": Image()} )					, embed_local_files=__SCREAMING_SNAKE_CASE ) as writer:
				writer.write({"image": image_path} )
				writer.finalize()
		__lowerCAmelCase:       List[str]          =			pa.BufferReader(output.getvalue() )
		__lowerCAmelCase:       pa.Table          =			pq.read_table(__SCREAMING_SNAKE_CASE )
		__lowerCAmelCase:       List[str]          =			pa_table.to_pydict()
		if embed_local_files:
				assert isinstance(out["image"][0]["path"]					, __SCREAMING_SNAKE_CASE )
				with open(__SCREAMING_SNAKE_CASE					, "rb" ) as f:
						assert out["image"][0]["bytes"] == f.read()
		else:
				assert out["image"][0]["path"] == image_path
				assert out["image"][0]["bytes"] is None






def     a__    (    )	->	Tuple:
		__lowerCAmelCase:       Dict          =			pa.schema([pa.field("col_1"					, pa.string()					, nullable=__SCREAMING_SNAKE_CASE )] )
		__lowerCAmelCase:       Any          =			pa.BufferOutputStream()
		with ArrowWriter(stream=__SCREAMING_SNAKE_CASE ) as writer:
				writer._build_writer(inferred_schema=__SCREAMING_SNAKE_CASE )
				assert writer._schema == pa.schema([pa.field("col_1"					, pa.string() )] )





"""simple docstring"""


import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
    slow,
)
from transformers.utils import is_sentencepiece_available


if is_sentencepiece_available():
			from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json

from ...test_tokenization_common import TokenizerTesterMixin


if is_sentencepiece_available():
			__A						   =			get_tests_dir("fixtures/test_sentencepiece.model")


if is_torch_available():
			from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right

__A						   =			128022
__A						   =			128028





@require_sentencepiece
class     snake_case	(				__snake_case,							unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_   :      Optional[int]         =  MaMaaaTokenizer
				SCREAMING_SNAKE_CASE_   :      Tuple         =  False
				SCREAMING_SNAKE_CASE_   :      str         =  False
				SCREAMING_SNAKE_CASE_   :      List[str]         =  True

				def 							lowercase_     (	self							:				List[str])->   str:



						'''simple docstring'''


						super().setUp()

						__lowerCAmelCase:       List[str]          =			["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"]
						__lowerCAmelCase:       List[str]          =			dict(zip(UpperCamelCase__     ,  range(len(UpperCamelCase__))))
						__lowerCAmelCase:       Optional[Any]          =			Path(self.tmpdirname)
						save_json(UpperCamelCase__     ,  save_dir / VOCAB_FILES_NAMES["vocab_file"])
						if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
								copyfile(UpperCamelCase__     ,  save_dir / VOCAB_FILES_NAMES["spm_file"])

						__lowerCAmelCase:       Optional[int]          =			MaMaaaTokenizer.from_pretrained(self.tmpdirname)
						tokenizer.save_pretrained(self.tmpdirname)

				def 							lowercase_     (	self							:				Optional[int]     ,  **UpperCamelCase__							:				Union[str, Any])->   Optional[int]:



						'''simple docstring'''


						return MaMaaaTokenizer.from_pretrained(self.tmpdirname     ,  **UpperCamelCase__)

				def 							lowercase_     (	self							:				Optional[int]     ,  UpperCamelCase__							:				str)->   List[Any]:



						'''simple docstring'''


						return (
						    "This is a test",
						    "This is a test",
						)

				def 							lowercase_     (	self							:				Union[str, Any])->   str:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			"</s>"
						__lowerCAmelCase:       Dict          =			0

						self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__)     ,  UpperCamelCase__)
						self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__)     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				str)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       List[str]          =			self.get_tokenizer()
						__lowerCAmelCase:       int          =			list(tokenizer.get_vocab().keys())

						self.assertEqual(vocab_keys[0]     ,  "</s>")
						self.assertEqual(vocab_keys[1]     ,  "<unk>")
						self.assertEqual(vocab_keys[-1]     ,  "<s>")
						self.assertEqual(len(UpperCamelCase__)     ,  tokenizer.vocab_size + len(tokenizer.get_added_vocab()))

				@unittest.skip("Skip this test while all models are still to be uploaded.")
				def 							lowercase_     (	self							:				Optional[Any])->   Any:



						'''simple docstring'''


						pass

				def 							lowercase_     (	self							:				Optional[int])->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.get_tokenizer()

						__lowerCAmelCase:       str          =			tokenizer.tokenize("This is a test")
						self.assertListEqual(UpperCamelCase__     ,  ["▁This", "▁is", "▁a", "▁t", "est"])

						self.assertListEqual(
						    tokenizer.convert_tokens_to_ids(UpperCamelCase__)     ,  [2, 3, 4, 5, 6]     ,  )

						__lowerCAmelCase:       Union[str, Any]          =			tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6])
						self.assertListEqual(UpperCamelCase__     ,  ["▁This", "▁is", "▁a", "▁t", "est"])

						__lowerCAmelCase:       Tuple          =			tokenizer.convert_tokens_to_string(UpperCamelCase__)
						self.assertEqual(UpperCamelCase__     ,  "This is a test")




				@slow
				def 							lowercase_     (	self							:				Optional[int])->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			{"input_ids": [[1_2_8_0_2_2, 1_1_0_1_0_8, 3_9_7, 1_1, 3_8_2_7_2, 2_2_4_7, 1_2_4_8_1_1, 2_8_5, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 3_9_5_3_4, 4_4_2_8, 3_9_7, 1_0_1_9, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 4_1_3_3_7, 1_6_7_8_6, 2_4_1, 7, 2_0_2_1_4, 1_7, 1_2_5_6_9_0, 1_0_3_9_8, 7, 4_4_3_7_8, 5_8_0_6_9, 6_8_3_4_2, 7_7_9_8, 7_3_4_3, 1_1, 2_9_9, 3_3_3_1_0, 4, 1_5_8, 3_7_3_5_0, 9_4_0_7_7, 4_5_6_9, 2_9_9, 3_3_3_1_0, 9_0, 4, 5_2_8_4_0, 2_9_0, 4, 3_1_2_7_0, 1_1_2, 2_9_9, 6_8_2, 4, 5_2_8_4_0, 3_9_9_5_3,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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
						# fmt: on

						self.tokenizer_integration_test_util(
						    expected_encoding=UpperCamelCase__     ,  model_name="facebook/m2m100_418M"     ,  revision="c168bae485c864188cf9aa0e4108b0b6934dc91e"     ,  )





@require_torch
@require_sentencepiece
@require_tokenizers
class     snake_case	(				unittest.TestCase  ):
				SCREAMING_SNAKE_CASE_   :      List[str]         =  """facebook/m2m100_418M"""
				SCREAMING_SNAKE_CASE_   :      List[str]         =  [
				    """In my opinion, there are two levels of response from the French government.""",
				    """NSA Affair Emphasizes Complete Lack of Debate on Intelligence""",
				]
				SCREAMING_SNAKE_CASE_   :      Tuple         =  [
				    """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
				    """L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
				]

				# fmt: off
				SCREAMING_SNAKE_CASE_   :      Any         =  [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2]

				@classmethod
				def 							lowercase_     (	cls							:				int)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       MaMaaaTokenizer          =			MaMaaaTokenizer.from_pretrained(
						    cls.checkpoint_name     ,  src_lang="en"     ,  tgt_lang="fr")
						__lowerCAmelCase:       Any          =			1
						return cls

				def 							lowercase_     (	self							:				int)->   Optional[int]:



						'''simple docstring'''


						self.assertEqual(self.tokenizer.get_lang_id("ar")     ,  1_2_8_0_0_6)
						self.assertEqual(self.tokenizer.get_lang_id("en")     ,  1_2_8_0_2_2)
						self.assertEqual(self.tokenizer.get_lang_id("ro")     ,  1_2_8_0_7_6)
						self.assertEqual(self.tokenizer.get_lang_id("mr")     ,  1_2_8_0_6_3)

				def 							lowercase_     (	self							:				int)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			self.tokenizer.get_vocab()
						self.assertEqual(len(UpperCamelCase__)     ,  self.tokenizer.vocab_size)
						self.assertEqual(vocab["<unk>"]     ,  3)
						self.assertIn(self.tokenizer.get_lang_token("en")     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Optional[int])->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			"en"
						__lowerCAmelCase:       Union[str, Any]          =			self.tokenizer.batch_encode_plus(self.src_text).input_ids[0]
						self.assertListEqual(self.expected_src_tokens     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				str)->   Tuple:



						'''simple docstring'''


						self.assertIn(UpperCamelCase__     ,  self.tokenizer.all_special_ids)
						# fmt: off
						__lowerCAmelCase:       Optional[Any]          =			[FR_CODE, 5_3_6_4, 8_2, 8_6_4_2, 4, 2_9_4, 4_7, 8, 1_4_0_2_8, 1_3_6, 3_2_8_6, 9_7_0_6, 6, 9_0_7_9_7, 6, 1_4_4_0_1_2, 1_6_2, 8_8_1_2_8, 3_0_0_6_1, 5, 2]
						# fmt: on
						__lowerCAmelCase:       Optional[Any]          =			self.tokenizer.decode(UpperCamelCase__     ,  skip_special_tokens=UpperCamelCase__)
						__lowerCAmelCase:       List[Any]          =			self.tokenizer.decode(generated_ids[1:]     ,  skip_special_tokens=UpperCamelCase__)
						self.assertEqual(UpperCamelCase__     ,  UpperCamelCase__)
						self.assertNotIn(self.tokenizer.eos_token     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Any)->   Optional[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			tempfile.mkdtemp()
						__lowerCAmelCase:       Union[str, Any]          =			self.tokenizer.lang_token_to_id
						self.tokenizer.save_pretrained(UpperCamelCase__)
						__lowerCAmelCase:       Tuple          =			MaMaaaTokenizer.from_pretrained(UpperCamelCase__)
						self.assertDictEqual(new_tok.lang_token_to_id     ,  UpperCamelCase__)

				@require_torch
				def 							lowercase_     (	self							:				List[str])->   str:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			"en"
						__lowerCAmelCase:       str          =			"fr"

						__lowerCAmelCase:       Optional[int]          =			self.tokenizer(self.src_text     ,  text_target=self.tgt_text     ,  padding=UpperCamelCase__     ,  return_tensors="pt")

						__lowerCAmelCase:       Optional[Any]          =			shift_tokens_right(
						    batch["labels"]     ,  self.tokenizer.pad_token_id     ,  self.tokenizer.eos_token_id)

						for k in batch:
								__lowerCAmelCase:       Tuple          =			batch[k].tolist()
						# batch = {k: v.tolist() for k,v in batch.items()}
						# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
						# batch.decoder_inputs_ids[0][0] ==
						assert batch.input_ids[1][0] == EN_CODE
						assert batch.input_ids[1][-1] == 2
						assert batch.labels[1][0] == FR_CODE
						assert batch.labels[1][-1] == 2
						assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]

				@require_torch
				def 							lowercase_     (	self							:				Dict)->   Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			"mr"
						self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("mr")])
						self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id])

						__lowerCAmelCase:       List[Any]          =			"zh"
						self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("zh")])
						self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id])

				@require_torch
				def 							lowercase_     (	self							:				Optional[int])->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       int          =			"mr"
						self.tokenizer._switch_to_target_mode()
						self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("mr")])
						self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id])
						self.tokenizer._switch_to_input_mode()
						self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id(self.tokenizer.src_lang)])

						__lowerCAmelCase:       List[str]          =			"zh"
						self.tokenizer._switch_to_target_mode()
						self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("zh")])
						self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id])
						self.tokenizer._switch_to_input_mode()
						self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id(self.tokenizer.src_lang)])




				@require_torch
				def 							lowercase_     (	self							:				Union[str, Any])->   Optional[int]:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.tokenizer._build_translation_inputs("A test"     ,  return_tensors="pt"     ,  src_lang="en"     ,  tgt_lang="ar")

						self.assertEqual(
						    nested_simplify(UpperCamelCase__)     ,  {
						        # en_XX, A, test, EOS
						        "input_ids": [[1_2_8_0_2_2, 5_8, 4_1_8_3, 2]],
						        "attention_mask": [[1, 1, 1, 1]],
						        # ar_AR
						        "forced_bos_token_id": 1_2_8_0_0_6,
						    }     ,  )


