




'''simple docstring'''


import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


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


_snake_case   :   str     							=	{'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

# See all BART models at https://huggingface.co/models?filter=bart
_snake_case   :   List[str]     							=	{
    'vocab_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/vocab.json',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/vocab.json',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json',
    },
    'merges_file': {
        'facebook/bart-base': 'https://huggingface.co/facebook/bart-base/resolve/main/merges.txt',
        'facebook/bart-large': 'https://huggingface.co/facebook/bart-large/resolve/main/merges.txt',
        'facebook/bart-large-mnli': 'https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt',
        'facebook/bart-large-cnn': 'https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt',
        'facebook/bart-large-xsum': 'https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt',
        'yjernite/bart_eli5': 'https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt',
    },
}

_snake_case   :   Optional[Any]     							=	{
    'facebook/bart-base': 1024,
    'facebook/bart-large': 1024,
    'facebook/bart-large-mnli': 1024,
    'facebook/bart-large-cnn': 1024,
    'facebook/bart-large-xsum': 1024,
    'yjernite/bart_eli5': 1024,
}
@lru_cache()
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       (
							    list(range(ord('''!'''   )				,		ord('''~'''   ) + 1   )   ) + list(range(ord('''¡'''   )				,		ord('''¬'''   ) + 1   )   ) + list(range(ord('''®'''   )				,		ord('''ÿ'''   ) + 1   )   )
							)
							_a			  =       bs[:]
							_a			  =       0
							for b in range(2**8   ):
														if b not in bs:
																					bs.append(UpperCamelCase   )
																					cs.append(2**8 + n   )
																					n += 1
							_a			  =       [chr(UpperCamelCase   ) for n in cs]
							return dict(zip(UpperCamelCase				,		UpperCamelCase   )   )
def 	snake_case_					(UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       set()
							_a			  =       word[0]
							for char in word[1:]:
														pairs.add((prev_char, char)   )
														_a			  =       char
							return pairs

class     A					(	_a					):
							lowercase_           =       VOCAB_FILES_NAMES
							lowercase_           =       PRETRAINED_VOCAB_FILES_MAP
							lowercase_           =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							lowercase_           =       ['input_ids', 'attention_mask']







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


														"""simple docstring"""


														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else bos_token
														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else eos_token
														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else sep_token
														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else cls_token
														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else unk_token
														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else pad_token

														# Mask token behave like a normal word, i.e. include the space before it
														_a			  =       AddedToken(lowerCAmelCase_							,    lstrip=lowerCAmelCase_							,    rstrip=lowerCAmelCase_      ) if isinstance(lowerCAmelCase_							,    lowerCAmelCase_      ) else mask_token

														super().__init__(
														    errors=lowerCAmelCase_							,    bos_token=lowerCAmelCase_							,    eos_token=lowerCAmelCase_							,    unk_token=lowerCAmelCase_							,    sep_token=lowerCAmelCase_							,    cls_token=lowerCAmelCase_							,    pad_token=lowerCAmelCase_							,    mask_token=lowerCAmelCase_							,    add_prefix_space=lowerCAmelCase_							,    **lowerCAmelCase_							,    )

														with open(lowerCAmelCase_							,    encoding='''utf-8'''      ) as vocab_handle:
																					_a			  =       json.load(lowerCAmelCase_      )
														_a			  =       {v: k for k, v in self.encoder.items()}
														_a			  =       errors  # how to handle errors in decoding
														_a			  =       bytes_to_unicode()
														_a			  =       {v: k for k, v in self.byte_encoder.items()}
														with open(lowerCAmelCase_							,    encoding='''utf-8'''      ) as merges_handle:
																					_a			  =       merges_handle.read().split('''\n'''      )[1:-1]
														_a			  =       [tuple(merge.split()      ) for merge in bpe_merges]
														_a			  =       dict(zip(lowerCAmelCase_							,    range(len(lowerCAmelCase_      )      )      )      )
														_a			  =       {}
														_a			  =       add_prefix_space

														# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
														_a			  =       re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'''      )







							@property
							def      __lowerCAmelCase    (						self :						str      )    ->							Optional[Any]:


														"""simple docstring"""


														return len(self.encoder      )







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


														"""simple docstring"""


														return dict(self.encoder							,    **self.added_tokens_encoder      )







							def      __lowerCAmelCase    (						self :						int							,    lowerCAmelCase_ :						int      )    ->							Optional[int]:


														"""simple docstring"""


														if token in self.cache:
																					return self.cache[token]
														_a			  =       tuple(lowerCAmelCase_      )
														_a			  =       get_pairs(lowerCAmelCase_      )

														if not pairs:
																					return token

														while True:
																					_a			  =       min(lowerCAmelCase_							,    key=lambda lowerCAmelCase_      : self.bpe_ranks.get(lowerCAmelCase_							,    float('''inf'''      )      )      )
																					if bigram not in self.bpe_ranks:
																												break
																					_a  ,							_a			  =       bigram
																					_a			  =       []
																					_a			  =       0
																					while i < len(lowerCAmelCase_      ):
																												try:
																																			_a			  =       word.index(lowerCAmelCase_							,    lowerCAmelCase_      )
																												except ValueError:
																																			new_word.extend(word[i:]      )
																																			break
																												else:
																																			new_word.extend(word[i:j]      )
																																			_a			  =       j

																												if word[i] == first and i < len(lowerCAmelCase_      ) - 1 and word[i + 1] == second:
																																			new_word.append(first + second      )
																																			i += 2
																												else:
																																			new_word.append(word[i]      )
																																			i += 1
																					_a			  =       tuple(lowerCAmelCase_      )
																					_a			  =       new_word
																					if len(lowerCAmelCase_      ) == 1:
																												break
																					else:
																												_a			  =       get_pairs(lowerCAmelCase_      )
														_a			  =       ''' '''.join(lowerCAmelCase_      )
														_a			  =       word
														return word







							def      __lowerCAmelCase    (						self :						Dict							,    lowerCAmelCase_ :						List[str]      )    ->							Union[str, Any]:


														"""simple docstring"""


														_a			  =       []
														for token in re.findall(self.pat							,    lowerCAmelCase_      ):
																					_a			  =       ''''''.join(
																					    self.byte_encoder[b] for b in token.encode('''utf-8'''      )      )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
																					bpe_tokens.extend(bpe_token for bpe_token in self.bpe(lowerCAmelCase_      ).split(''' '''      )      )
														return bpe_tokens







							def      __lowerCAmelCase    (						self :						Optional[int]							,    lowerCAmelCase_ :						Any      )    ->							List[Any]:


														"""simple docstring"""


														return self.encoder.get(lowerCAmelCase_							,    self.encoder.get(self.unk_token      )      )







							def      __lowerCAmelCase    (						self :						Any							,    lowerCAmelCase_ :						List[Any]      )    ->							List[Any]:


														"""simple docstring"""


														return self.decoder.get(lowerCAmelCase_      )







							def      __lowerCAmelCase    (						self :						int							,    lowerCAmelCase_ :						Any      )    ->							Union[str, Any]:


														"""simple docstring"""


														_a			  =       ''''''.join(lowerCAmelCase_      )
														_a			  =       bytearray([self.byte_decoder[c] for c in text]      ).decode('''utf-8'''							,    errors=self.errors      )
														return text







							def      __lowerCAmelCase    (						self :						Union[str, Any]							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						Optional[str] = None      )    ->							Tuple[str]:


														"""simple docstring"""


														if not os.path.isdir(lowerCAmelCase_      ):
																					logger.error(F'Vocabulary path ({save_directory}) should be a directory'      )
																					return
														_a			  =       os.path.join(
														    lowerCAmelCase_							,    (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )
														_a			  =       os.path.join(
														    lowerCAmelCase_							,    (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']      )

														with open(lowerCAmelCase_							,    '''w'''							,    encoding='''utf-8'''      ) as f:
																					f.write(json.dumps(self.encoder							,    indent=2							,    sort_keys=lowerCAmelCase_							,    ensure_ascii=lowerCAmelCase_      ) + '''\n'''      )

														_a			  =       0
														with open(lowerCAmelCase_							,    '''w'''							,    encoding='''utf-8'''      ) as writer:
																					writer.write('''#version: 0.2\n'''      )
																					for bpe_tokens, token_index in sorted(self.bpe_ranks.items()							,    key=lambda lowerCAmelCase_      : kv[1]      ):
																												if index != token_index:
																																			logger.warning(
																																			    F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
																																			    ''' Please check that the tokenizer is not corrupted!'''      )
																																			_a			  =       token_index
																												writer.write(''' '''.join(lowerCAmelCase_      ) + '''\n'''      )
																												index += 1

														return vocab_file, merge_file







							def      __lowerCAmelCase    (						self :						List[str]							,    lowerCAmelCase_ :						List[int]							,    lowerCAmelCase_ :						Optional[List[int]] = None      )    ->							List[int]:


														"""simple docstring"""


														if token_ids_a is None:
																					return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
														_a			  =       [self.cls_token_id]
														_a			  =       [self.sep_token_id]
														return cls + token_ids_a + sep + sep + token_ids_a + sep







							def      __lowerCAmelCase    (						self :						Any							,    lowerCAmelCase_ :						List[int]							,    lowerCAmelCase_ :						Optional[List[int]] = None							,    lowerCAmelCase_ :						bool = False      )    ->							List[int]:


														"""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_      )

														if token_ids_a is None:
																					return [1] + ([0] * len(lowerCAmelCase_      )) + [1]
														return [1] + ([0] * len(lowerCAmelCase_      )) + [1, 1] + ([0] * len(lowerCAmelCase_      )) + [1]







							def      __lowerCAmelCase    (						self :						Dict							,    lowerCAmelCase_ :						List[int]							,    lowerCAmelCase_ :						Optional[List[int]] = None      )    ->							List[int]:


														"""simple docstring"""


														_a			  =       [self.sep_token_id]
														_a			  =       [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      __lowerCAmelCase    (						self :						Union[str, Any]							,    lowerCAmelCase_ :						Any							,    lowerCAmelCase_ :						Any=False							,    **lowerCAmelCase_ :						List[str]      )    ->							int:


														"""simple docstring"""


														_a			  =       kwargs.pop('''add_prefix_space'''							,    self.add_prefix_space      )
														if (is_split_into_words or add_prefix_space) and (len(lowerCAmelCase_      ) > 0 and not text[0].isspace()):
																					_a			  =       ''' ''' + text
														return (text, kwargs)







'''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     A					(	_a					):







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







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


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]      )							,    type=pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Dict:


														"""simple docstring"""


														with self.assertRaises(lowerCAmelCase_      ):
																					_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''bool'''      )							,    type=Value('''int64'''      )      )      )







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







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


														"""simple docstring"""


														with self.assertRaises((TypeError, pa.lib.ArrowInvalid)      ):
																					_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    type=Value('''int64'''      )      )      )







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


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([1, 2, 3]							,    try_type=Value('''int32'''      )      )      )
														self.assertEqual(arr.type							,    pa.intaa()      )







							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=Value('''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







							def      __lowerCAmelCase    (						self :						List[Any]      )    ->							str:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







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


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Tuple:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence([[[1, 2, 3]]]							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    ArrayaDExtensionType((1, 3)							,    '''int64'''      )      )







							def      __lowerCAmelCase    (						self :						List[str]      )    ->							Any:


														"""simple docstring"""


														_a			  =       pa.array(TypedSequence(['''foo''', '''bar''']							,    try_type=ArrayaD((1, 3)							,    '''int64'''      )      )      )
														self.assertEqual(arr.type							,    pa.string()      )







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


														"""simple docstring"""


														import PIL.Image

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



def 	snake_case_					(UpperCamelCase :						Union[str, Any]				,		UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferReader(UpperCamelCase   ) if isinstance(UpperCamelCase				,		pa.Buffer   ) else pa.memory_map(UpperCamelCase   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       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_					(UpperCamelCase :						Dict				,		UpperCamelCase :						str   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		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'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       Features({'''labels''': ClassLabel(names=['''neg''', '''pos''']   )}   )
							with ArrowWriter(stream=UpperCamelCase				,		features=UpperCamelCase   ) as writer:
														writer.write({'''labels''': 0}   )
														writer.write({'''labels''': 1}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert writer._schema == features.arrow_schema
							assert writer._schema.metadata == features.arrow_schema.metadata
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							_a			  =       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(UpperCamelCase   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=[1, 2]   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														with pytest.raises(UpperCamelCase   ):
																					writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=10   )
																					writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=10   )
																					_a  ,							_a			  =       writer.finalize()
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 2, 10]   )
def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=1   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=2   )
														_a  ,							_a			  =       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_					(UpperCamelCase :						Dict				,		UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
														writer.write_batch({'''col_1''': [], '''col_2''': []}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		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_					(UpperCamelCase :						Any				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		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_					(UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) 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]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		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:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
														_a			  =       os.path.join(UpperCamelCase				,		'''test.arrow'''   )
														with ArrowWriter(path=UpperCamelCase				,		schema=pa.schema(UpperCamelCase   )   ) as writer:
																					writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
																					_a  ,							_a			  =       writer.finalize()
														assert num_examples == 2
														assert num_bytes > 0
														assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
														_check_output(UpperCamelCase				,		1   )
def 	snake_case_					(UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							if pa.types.is_list(UpperCamelCase   ):
														return get_base_dtype(arr_type.value_type   )
							else:
														return arr_type
def 	snake_case_					(UpperCamelCase :						Optional[int]				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							if isinstance(lst[0]				,		UpperCamelCase   ):
														change_first_primitive_element_in_list(lst[0]				,		UpperCamelCase   )
							else:
														_a			  =       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_					(UpperCamelCase :						int				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.array(TypedSequence(UpperCamelCase				,		optimized_int_type=UpperCamelCase   )   )
							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_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						str				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype

							# not in range
							if col != "other":
														# avoids errors due to in-place modifications
														_a			  =       copy.deepcopy(UpperCamelCase   )
														_a			  =       np.iinfo(expected_dtype.to_pandas_dtype()   ).max + 1
														change_first_primitive_element_in_list(UpperCamelCase				,		UpperCamelCase   )
														_a			  =       pa.array(OptimizedTypedSequence(UpperCamelCase				,		col=UpperCamelCase   )   )
														assert get_base_dtype(arr.type   ) == pa.intaa()
@pytest.mark.parametrize('''raise_exception'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						Optional[Any]				,		UpperCamelCase :						Optional[Any]   ):





							'''simple docstring'''


							_a			  =       str(tmp_path / '''dataset-train.arrow'''   )
							try:
														with ArrowWriter(path=UpperCamelCase   ) 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_					(UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							_a			  =       '''mock://dataset-train.arrow'''
							with ArrowWriter(path=UpperCamelCase				,		storage_options=mockfs.storage_options   ) as writer:
														assert isinstance(writer._fs				,		type(UpperCamelCase   )   )
														assert writer._fs.storage_options == mockfs.storage_options
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							assert mockfs.exists(UpperCamelCase   )
def 	snake_case_					():





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(stream=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							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_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							import PIL.Image

							_a			  =       str(tmp_path / '''test_image_rgb.jpg'''   )
							PIL.Image.fromarray(np.zeros((5, 5)				,		dtype=np.uinta   )   ).save(UpperCamelCase				,		format='''png'''   )
							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(
							    stream=UpperCamelCase				,		features=Features({'''image''': Image()}   )				,		embed_local_files=UpperCamelCase   ) as writer:
														writer.write({'''image''': image_path}   )
														writer.finalize()
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							_a			  =       pa_table.to_pydict()
							if embed_local_files:
														assert isinstance(out['''image'''][0]['''path''']				,		UpperCamelCase   )
														with open(UpperCamelCase				,		'''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'''


							_a			  =       pa.schema([pa.field('''col_1'''				,		pa.string()				,		nullable=UpperCamelCase   )]   )
							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(stream=UpperCamelCase   ) as writer:
														writer._build_writer(inferred_schema=UpperCamelCase   )
														assert writer._schema == pa.schema([pa.field('''col_1'''				,		pa.string()   )]   )

