


'''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        lowercase__    (		_snake_case   ):





							'''simple docstring'''


							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Any							= pa.array(TypedSequence([1, 2, 3]    )    )
											self.assertEqual(arr.type       ,   pa.intaa()    )






							def UpperCAmelCase_      (       self    ):
											with self.assertRaises(__snake_case    ):
															_SCREAMING_SNAKE_CASE					:			List[str]							= pa.array(TypedSequence([1, 2, 3]    )       ,   type=pa.intaa()    )






							def UpperCAmelCase_      (       self    ):
											with self.assertRaises(__snake_case    ):
															_SCREAMING_SNAKE_CASE					:			Dict							= pa.array(TypedSequence([1, 2, 3]       ,   try_type=Value("""bool"""    )       ,   type=Value("""int64"""    )    )    )






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






							def UpperCAmelCase_      (       self    ):
											with self.assertRaises((TypeError, pa.lib.ArrowInvalid)    ):
															_SCREAMING_SNAKE_CASE					:			str							= pa.array(TypedSequence(["""foo""", """bar"""]       ,   type=Value("""int64"""    )    )    )






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= pa.array(TypedSequence([1, 2, 3]       ,   try_type=Value("""int32"""    )    )    )
											self.assertEqual(arr.type       ,   pa.intaa()    )






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






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= pa.array(TypedSequence([[[1, 2, 3]]]       ,   type=ArrayaD((1, 3)       ,   """int64"""    )    )    )
											self.assertEqual(arr.type       ,   ArrayaDExtensionType((1, 3)       ,   """int64"""    )    )






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






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			str							= pa.array(TypedSequence([[[1, 2, 3]]]       ,   try_type=ArrayaD((1, 3)       ,   """int64"""    )    )    )
											self.assertEqual(arr.type       ,   ArrayaDExtensionType((1, 3)       ,   """int64"""    )    )






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






							@require_pil
							def UpperCAmelCase_      (       self    ):
											import PIL.Image

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







def      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Any							= pa.BufferReader(SCREAMING_SNAKE_CASE__	) if isinstance(SCREAMING_SNAKE_CASE__				, pa.Buffer	) else pa.memory_map(SCREAMING_SNAKE_CASE__	)
				_SCREAMING_SNAKE_CASE					:			str							= pa.ipc.open_stream(SCREAMING_SNAKE_CASE__	)
				_SCREAMING_SNAKE_CASE					:			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, 10]	)
@pytest.mark.parametrize(
    """fields"""				, [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Optional[int]							= pa.BufferOutputStream()
				_SCREAMING_SNAKE_CASE					:			List[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({"""col_1""": """foo""", """col_2""": 1}	)
								writer.write({"""col_1""": """bar""", """col_2""": 2}	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				if not fields:
								_SCREAMING_SNAKE_CASE					:			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      snake_case_  (    ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Any							= pa.BufferOutputStream()
				_SCREAMING_SNAKE_CASE					:			Optional[int]							= 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}	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			str							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				assert writer._schema == features.arrow_schema
				assert writer._schema.metadata == features.arrow_schema.metadata
				_SCREAMING_SNAKE_CASE					:			str							= pa.BufferReader(output.getvalue()	)
				_SCREAMING_SNAKE_CASE					:			str							= pa.ipc.open_stream(SCREAMING_SNAKE_CASE__	)
				_SCREAMING_SNAKE_CASE					:			pa.Table							= f.read_all()
				_SCREAMING_SNAKE_CASE					:			Optional[int]							= 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, 10]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			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, 2]	)
												_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Tuple							= writer.finalize()







@pytest.mark.parametrize("""writer_batch_size"""				, [None, 2, 10]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Tuple							= 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=10	)
												writer.write({"""col_1""": """bar""", """col_2""": 2}				, key=10	)
												_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Any							= writer.finalize()







@pytest.mark.parametrize("""writer_batch_size"""				, [None, 2, 10]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			str							= 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	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Optional[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, 10]	)
@pytest.mark.parametrize(
    """fields"""				, [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Optional[Any]							= pa.BufferOutputStream()
				_SCREAMING_SNAKE_CASE					:			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""": []}	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Optional[int]							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				if not fields:
								_SCREAMING_SNAKE_CASE					:			List[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, 10]	)
@pytest.mark.parametrize(
    """fields"""				, [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			List[str]							= pa.BufferOutputStream()
				_SCREAMING_SNAKE_CASE					:			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_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}	)	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Tuple							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				if not fields:
								_SCREAMING_SNAKE_CASE					:			str							= {"""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, 10]	)
@pytest.mark.parametrize(
    """fields"""				, [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]	)
def      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Optional[int]							= pa.BufferOutputStream()
				_SCREAMING_SNAKE_CASE					:			Tuple							= 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]}	)	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			List[Any]							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				if not fields:
								_SCREAMING_SNAKE_CASE					:			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      snake_case_  (    ):







				"""simple docstring"""





				with tempfile.TemporaryDirectory() as tmp_dir:
								_SCREAMING_SNAKE_CASE					:			List[Any]							= {"""col_1""": pa.string(), """col_2""": pa.intaa()}
								_SCREAMING_SNAKE_CASE					:			Optional[int]							= 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]}	)
												_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= 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      snake_case_  (    SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				if pa.types.is_list(SCREAMING_SNAKE_CASE__	):
								return get_base_dtype(arr_type.value_type	)
				else:
								return arr_type







def      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				if isinstance(lst[0]				, SCREAMING_SNAKE_CASE__	):
								change_first_primitive_element_in_list(lst[0]				, SCREAMING_SNAKE_CASE__	)
				else:
								_SCREAMING_SNAKE_CASE					:			Dict							= 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      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Tuple							= 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      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Tuple							= 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
								_SCREAMING_SNAKE_CASE					:			Optional[Any]							= copy.deepcopy(SCREAMING_SNAKE_CASE__	)
								_SCREAMING_SNAKE_CASE					:			Optional[int]							= np.iinfo(expected_dtype.to_pandas_dtype()	).max + 1
								change_first_primitive_element_in_list(SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	)
								_SCREAMING_SNAKE_CASE					:			Dict							= 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      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Optional[int]							= 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      snake_case_  (    SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Optional[int]							= """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}	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			int							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				assert mockfs.exists(SCREAMING_SNAKE_CASE__	)







def      snake_case_  (    ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Dict							= 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}	)
								_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			Optional[int]							= writer.finalize()
				assert num_examples == 2
				assert num_bytes > 0
				_SCREAMING_SNAKE_CASE					:			str							= pa.BufferReader(output.getvalue()	)
				_SCREAMING_SNAKE_CASE					:			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      snake_case_  (    SCREAMING_SNAKE_CASE__				, SCREAMING_SNAKE_CASE__	):







				"""simple docstring"""





				import PIL.Image

				_SCREAMING_SNAKE_CASE					:			Tuple							= str(tmp_path / """test_image_rgb.jpg"""	)
				PIL.Image.fromarray(np.zeros((5, 5)				, dtype=np.uinta	)	).save(SCREAMING_SNAKE_CASE__				, format="""png"""	)
				_SCREAMING_SNAKE_CASE					:			List[Any]							= 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()
				_SCREAMING_SNAKE_CASE					:			List[str]							= pa.BufferReader(output.getvalue()	)
				_SCREAMING_SNAKE_CASE					:			pa.Table							= pq.read_table(SCREAMING_SNAKE_CASE__	)
				_SCREAMING_SNAKE_CASE					:			Optional[Any]							= 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      snake_case_  (    ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			List[Any]							= pa.schema([pa.field("""col_1"""				, pa.string()				, nullable=SCREAMING_SNAKE_CASE__	)]	)
				_SCREAMING_SNAKE_CASE					:			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 os
from shutil import copyfile
from typing import List, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
				from .tokenization_mbart import MBartTokenizer
else:
				UpperCAmelCase_						:  List[str]				  =						None


UpperCAmelCase_						:  Tuple				  =						logging.get_logger(__name__)


UpperCAmelCase_						:  List[Any]				  =						{'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}

UpperCAmelCase_						:  Dict				  =						{
    'vocab_file': {
        'facebook/mbart-large-en-ro': (
            'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model'
        ),
        'facebook/mbart-large-cc25': (
            'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model'
        ),
    },
    'tokenizer_file': {
        'facebook/mbart-large-en-ro': 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/tokenizer.json',
        'facebook/mbart-large-cc25': 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/tokenizer.json',
    },
}

UpperCAmelCase_						:  str				  =						{
    'facebook/mbart-large-en-ro': 1024,
    'facebook/mbart-large-cc25': 1024,
}

# fmt: off
UpperCAmelCase_						:  List[str]				  =						['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN']





class        lowercase__    (		_snake_case   ):





							'''simple docstring'''


							A_				: Any       =    VOCAB_FILES_NAMES
							A_				: List[str]       =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							A_				: Any       =    PRETRAINED_VOCAB_FILES_MAP
							A_				: Tuple       =    ["""input_ids""", """attention_mask"""]
							A_				: Dict       =    MBartTokenizer

							A_				: List[int]       =    []
							A_				: List[int]       =    []






							def __init__(       self       ,   __snake_case=None       ,   __snake_case=None       ,   __snake_case="<s>"       ,   __snake_case="</s>"       ,   __snake_case="</s>"       ,   __snake_case="<s>"       ,   __snake_case="<unk>"       ,   __snake_case="<pad>"       ,   __snake_case="<mask>"       ,   __snake_case=None       ,   __snake_case=None       ,   __snake_case=None       ,   **__snake_case       ,   ):
											# Mask token behave like a normal word, i.e. include the space before it
											_SCREAMING_SNAKE_CASE					:			List[Any]							= AddedToken(__snake_case       ,   lstrip=__snake_case       ,   rstrip=__snake_case    ) if isinstance(__snake_case       ,   __snake_case    ) else mask_token

											super().__init__(
											    vocab_file=__snake_case       ,   tokenizer_file=__snake_case       ,   bos_token=__snake_case       ,   eos_token=__snake_case       ,   sep_token=__snake_case       ,   cls_token=__snake_case       ,   unk_token=__snake_case       ,   pad_token=__snake_case       ,   mask_token=__snake_case       ,   src_lang=__snake_case       ,   tgt_lang=__snake_case       ,   additional_special_tokens=__snake_case       ,   **__snake_case       ,   )

											_SCREAMING_SNAKE_CASE					:			List[str]							= vocab_file
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= False if not self.vocab_file else True

											_SCREAMING_SNAKE_CASE					:			int							= FAIRSEQ_LANGUAGE_CODES.copy()

											if additional_special_tokens is not None:
															# Only add those special tokens if they are not already there.
															_additional_special_tokens.extend(
															    [t for t in additional_special_tokens if t not in _additional_special_tokens]    )

											self.add_special_tokens({"""additional_special_tokens""": _additional_special_tokens}    )
											_SCREAMING_SNAKE_CASE					:			str							= {
											    lang_code: self.convert_tokens_to_ids(__snake_case    ) for lang_code in FAIRSEQ_LANGUAGE_CODES
											}

											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= src_lang if src_lang is not None else """en_XX"""
											_SCREAMING_SNAKE_CASE					:			str							= self.convert_tokens_to_ids(self._src_lang    )
											_SCREAMING_SNAKE_CASE					:			Any							= tgt_lang
											self.set_src_lang_special_tokens(self._src_lang    )






							@property
							def UpperCAmelCase_      (       self    ):
											return self._src_lang






							@src_lang.setter
							def UpperCAmelCase_      (       self       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			Any							= new_src_lang
											self.set_src_lang_special_tokens(self._src_lang    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case = None    ):
											if token_ids_a is None:
															return self.prefix_tokens + token_ids_a + self.suffix_tokens
											# 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.suffix_tokens






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case = None    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= [self.sep_token_id]
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= [self.cls_token_id]

											if token_ids_a is None:
															return len(cls + token_ids_a + sep    ) * [0]
											return len(cls + token_ids_a + sep + sep + token_ids_a + sep    ) * [0]






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   **__snake_case    ):
											if src_lang is None or tgt_lang is None:
															raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""    )
											_SCREAMING_SNAKE_CASE					:			Dict							= src_lang
											_SCREAMING_SNAKE_CASE					:			List[Any]							= self(__snake_case       ,   add_special_tokens=__snake_case       ,   return_tensors=__snake_case       ,   **__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Dict							= self.convert_tokens_to_ids(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= tgt_lang_id
											return inputs






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case = "en_XX"       ,   __snake_case = None       ,   __snake_case = "ro_RO"       ,   **__snake_case       ,   ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= src_lang
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= tgt_lang
											return super().prepare_seqaseq_batch(__snake_case       ,   __snake_case       ,   **__snake_case    )






							def UpperCAmelCase_      (       self    ):
											return self.set_src_lang_special_tokens(self.src_lang    )






							def UpperCAmelCase_      (       self    ):
											return self.set_tgt_lang_special_tokens(self.tgt_lang    )






							def UpperCAmelCase_      (       self       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= self.convert_tokens_to_ids(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			str							= []
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= [self.eos_token_id, self.cur_lang_code]

											_SCREAMING_SNAKE_CASE					:			int							= self.convert_ids_to_tokens(self.prefix_tokens    )
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= self.convert_ids_to_tokens(self.suffix_tokens    )

											_SCREAMING_SNAKE_CASE					:			Optional[int]							= processors.TemplateProcessing(
											    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,   pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,   special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,   self.prefix_tokens + self.suffix_tokens    )    )       ,   )






							def UpperCAmelCase_      (       self       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= self.convert_tokens_to_ids(__snake_case    )
											_SCREAMING_SNAKE_CASE					:			List[str]							= []
											_SCREAMING_SNAKE_CASE					:			Tuple							= [self.eos_token_id, self.cur_lang_code]

											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= self.convert_ids_to_tokens(self.prefix_tokens    )
											_SCREAMING_SNAKE_CASE					:			str							= self.convert_ids_to_tokens(self.suffix_tokens    )

											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= processors.TemplateProcessing(
											    single=prefix_tokens_str + ["""$A"""] + suffix_tokens_str       ,   pair=prefix_tokens_str + ["""$A""", """$B"""] + suffix_tokens_str       ,   special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str       ,   self.prefix_tokens + self.suffix_tokens    )    )       ,   )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case = None    ):
											if not self.can_save_slow_tokenizer:
															raise ValueError(
															    """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
															    """tokenizer."""    )

											if not os.path.isdir(__snake_case    ):
															logger.error(f"""Vocabulary path ({save_directory}) should be a directory."""    )
															return
											_SCREAMING_SNAKE_CASE					:			List[str]							= os.path.join(
											    __snake_case       ,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]    )

											if os.path.abspath(self.vocab_file    ) != os.path.abspath(__snake_case    ):
															copyfile(self.vocab_file       ,   __snake_case    )

											return (out_vocab_file,)




