




'''simple docstring'''


from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


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

class     A					(	_UpperCAmelCase					):
							lowercase_           =       ['pixel_values']







							def __init__(						self :						Dict							,    lowerCAmelCase_ :						bool = True							,    lowerCAmelCase_ :						Dict[str, int] = None							,    lowerCAmelCase_ :						PILImageResampling = PILImageResampling.BICUBIC							,    lowerCAmelCase_ :						bool = True							,    lowerCAmelCase_ :						Dict[str, int] = None							,    lowerCAmelCase_ :						bool = True							,    lowerCAmelCase_ :						Union[int, float] = 1 / 2_55							,    lowerCAmelCase_ :						bool = True							,    lowerCAmelCase_ :						Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN							,    lowerCAmelCase_ :						Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD							,    **lowerCAmelCase_ :						Tuple							,    )    ->							None:


														"""simple docstring"""


														super().__init__(**lowerCamelCase_      )
														_a			  =       size if size is not None else {'''shortest_edge''': 2_24}
														_a			  =       get_size_dict(lowerCamelCase_							,    default_to_square=lowerCamelCase_      )
														_a			  =       crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
														_a			  =       get_size_dict(lowerCamelCase_							,    param_name='''crop_size'''      )

														_a			  =       do_resize
														_a			  =       size
														_a			  =       resample
														_a			  =       do_center_crop
														_a			  =       crop_size
														_a			  =       do_rescale
														_a			  =       rescale_factor
														_a			  =       do_normalize
														_a			  =       image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
														_a			  =       image_std if image_std is not None else IMAGENET_DEFAULT_STD







							def      __lowerCAmelCase    (						self :						List[str]							,    lowerCAmelCase_ :						np.ndarray							,    lowerCAmelCase_ :						Dict[str, int]							,    lowerCAmelCase_ :						PILImageResampling = PILImageResampling.BICUBIC							,    lowerCAmelCase_ :						Optional[Union[str, ChannelDimension]] = None							,    **lowerCAmelCase_ :						Any							,    )    ->							np.ndarray:


														"""simple docstring"""


														_a			  =       get_size_dict(lowerCamelCase_							,    default_to_square=lowerCamelCase_      )
														# size_dict is a dict with either keys "height" and "width" or "shortest_edge"
														if "shortest_edge" in size:
																					_a			  =       int((2_56 / 2_24) * size['''shortest_edge''']      )
																					_a			  =       get_resize_output_image_size(lowerCamelCase_							,    size=lowerCamelCase_							,    default_to_square=lowerCamelCase_      )
																					_a			  =       {'''height''': output_size[0], '''width''': output_size[1]}
														if "height" not in size_dict or "width" not in size_dict:
																					raise ValueError(
																					    F'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'      )
														return resize(
														    lowerCamelCase_							,    size=(size_dict['''height'''], size_dict['''width'''])							,    resample=lowerCamelCase_							,    data_format=lowerCamelCase_							,    **lowerCamelCase_      )







							def      __lowerCAmelCase    (						self :						Tuple							,    lowerCAmelCase_ :						np.ndarray							,    lowerCAmelCase_ :						Dict[str, int]							,    lowerCAmelCase_ :						Optional[Union[str, ChannelDimension]] = None							,    **lowerCAmelCase_ :						int							,    )    ->							np.ndarray:


														"""simple docstring"""


														_a			  =       get_size_dict(lowerCamelCase_      )
														if "height" not in size or "width" not in size:
																					raise ValueError(F'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'      )
														return center_crop(lowerCamelCase_							,    size=(size['''height'''], size['''width'''])							,    data_format=lowerCamelCase_							,    **lowerCamelCase_      )







							def      __lowerCAmelCase    (						self :						Optional[Any]							,    lowerCAmelCase_ :						np.ndarray							,    lowerCAmelCase_ :						Union[int, float]							,    lowerCAmelCase_ :						Optional[Union[str, ChannelDimension]] = None							,    **lowerCAmelCase_ :						Any							,    )    ->							np.ndarray:


														"""simple docstring"""


														return rescale(lowerCamelCase_							,    scale=lowerCamelCase_							,    data_format=lowerCamelCase_							,    **lowerCamelCase_      )







							def      __lowerCAmelCase    (						self :						Optional[int]							,    lowerCAmelCase_ :						np.ndarray							,    lowerCAmelCase_ :						Union[float, List[float]]							,    lowerCAmelCase_ :						Union[float, List[float]]							,    lowerCAmelCase_ :						Optional[Union[str, ChannelDimension]] = None							,    **lowerCAmelCase_ :						str							,    )    ->							np.ndarray:


														"""simple docstring"""


														return normalize(lowerCamelCase_							,    mean=lowerCamelCase_							,    std=lowerCamelCase_							,    data_format=lowerCamelCase_							,    **lowerCamelCase_      )







							def      __lowerCAmelCase    (						self :						Union[str, Any]							,    lowerCAmelCase_ :						ImageInput							,    lowerCAmelCase_ :						Optional[bool] = None							,    lowerCAmelCase_ :						Optional[Dict[str, int]] = None							,    lowerCAmelCase_ :						PILImageResampling = None							,    lowerCAmelCase_ :						Optional[bool] = None							,    lowerCAmelCase_ :						Optional[Dict[str, int]] = None							,    lowerCAmelCase_ :						Optional[bool] = None							,    lowerCAmelCase_ :						Optional[float] = None							,    lowerCAmelCase_ :						Optional[bool] = None							,    lowerCAmelCase_ :						Optional[Union[float, Iterable[float]]] = None							,    lowerCAmelCase_ :						Optional[Union[float, Iterable[float]]] = None							,    lowerCAmelCase_ :						Optional[TensorType] = None							,    lowerCAmelCase_ :						ChannelDimension = ChannelDimension.FIRST							,    **lowerCAmelCase_ :						Optional[int]							,    )    ->							BatchFeature:


														"""simple docstring"""


														_a			  =       do_resize if do_resize is not None else self.do_resize
														_a			  =       resample if resample is not None else self.resample
														_a			  =       do_center_crop if do_center_crop is not None else self.do_center_crop
														_a			  =       do_rescale if do_rescale is not None else self.do_rescale
														_a			  =       rescale_factor if rescale_factor is not None else self.rescale_factor
														_a			  =       do_normalize if do_normalize is not None else self.do_normalize
														_a			  =       image_mean if image_mean is not None else self.image_mean
														_a			  =       image_std if image_std is not None else self.image_std

														_a			  =       size if size is not None else self.size
														_a			  =       get_size_dict(lowerCamelCase_							,    default_to_square=lowerCamelCase_      )
														_a			  =       crop_size if crop_size is not None else self.crop_size
														_a			  =       get_size_dict(lowerCamelCase_							,    param_name='''crop_size'''      )

														_a			  =       make_list_of_images(lowerCamelCase_      )

														if not valid_images(lowerCamelCase_      ):
																					raise ValueError(
																					    '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
																					    '''torch.Tensor, tf.Tensor or jax.ndarray.'''      )

														if do_resize and size is None:
																					raise ValueError('''Size must be specified if do_resize is True.'''      )

														if do_center_crop and crop_size is None:
																					raise ValueError('''Crop size must be specified if do_center_crop is True.'''      )

														if do_rescale and rescale_factor is None:
																					raise ValueError('''Rescale factor must be specified if do_rescale is True.'''      )

														if do_normalize and (image_mean is None or image_std is None):
																					raise ValueError('''Image mean and std must be specified if do_normalize is True.'''      )

														# All transformations expect numpy arrays.
														_a			  =       [to_numpy_array(lowerCamelCase_      ) for image in images]

														if do_resize:
																					_a			  =       [self.resize(lowerCamelCase_							,    lowerCamelCase_							,    lowerCamelCase_      ) for image in images]

														if do_center_crop:
																					_a			  =       [self.center_crop(lowerCamelCase_							,    lowerCamelCase_      ) for image in images]

														if do_rescale:
																					_a			  =       [self.rescale(lowerCamelCase_							,    lowerCamelCase_      ) for image in images]

														if do_normalize:
																					_a			  =       [self.normalize(lowerCamelCase_							,    lowerCamelCase_							,    lowerCamelCase_      ) for image in images]

														_a			  =       [to_channel_dimension_format(lowerCamelCase_							,    lowerCamelCase_      ) for image in images]

														_a			  =       {'''pixel_values''': images}
														return BatchFeature(data=lowerCamelCase_							,    tensor_type=lowerCamelCase_      )







'''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()   )]   )

