from typing import Dict, List, Optional, Union

import numpy as np

from .feature_extraction_utils import BatchFeature, FeatureExtractionMixin
from .utils import PaddingStrategy, TensorType, is_tf_tensor, is_torch_tensor, logging, to_numpy


__lowerCamelCase    :				Optional[Any]							     =	logging.get_logger(__name__)







class __snake_case       (		lowerCamelCase_	):




   def __init__(					self    :       Any ,			_lowercase    :       int ,			_lowercase    :       int ,			_lowercase    :       float ,			**_lowercase    :       Optional[int]   ):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   feature_size
     SCREAMING_SNAKE_CASE__    							=   sampling_rate
     SCREAMING_SNAKE_CASE__    							=   padding_value

     SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""padding_side""" ,			"""right"""   )
     SCREAMING_SNAKE_CASE__    							=   kwargs.pop("""return_attention_mask""" ,			_lowercase   )

     super().__init__(**_lowercase   )




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       Union[
           BatchFeature,
           List[BatchFeature],
           Dict[str, BatchFeature],
           Dict[str, List[BatchFeature]],
           List[Dict[str, BatchFeature]],
       ] ,			_lowercase    :       Union[bool, str, PaddingStrategy] = True ,			_lowercase    :       Optional[int] = None ,			_lowercase    :       bool = False ,			_lowercase    :       Optional[int] = None ,			_lowercase    :       Optional[bool] = None ,			_lowercase    :       Optional[Union[str, TensorType]] = None ,			):



     """simple docstring"""






     if isinstance(_lowercase ,			(list, tuple)   ) and isinstance(processed_features[0] ,			(dict, BatchFeature)   ):
       SCREAMING_SNAKE_CASE__    							=   {
           key: [example[key] for example in processed_features] for key in processed_features[0].keys()
       }

     # The model's main input name, usually `input_values`, has be passed for padding
     if self.model_input_names[0] not in processed_features:
       raise ValueError(
           """You should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature`"""
           f""" to this method that includes {self.model_input_names[0]}, but you provided"""
           f""" {list(processed_features.keys()   )}"""   )

     SCREAMING_SNAKE_CASE__    							=   processed_features[self.model_input_names[0]]
     SCREAMING_SNAKE_CASE__    							=   (
         return_attention_mask if return_attention_mask is not None else self.return_attention_mask
     )

     if len(_lowercase   ) == 0:
       if return_attention_mask:
         SCREAMING_SNAKE_CASE__    							=   []
       return processed_features

     # If we have PyTorch/TF tensors or lists as inputs, we cast them as Numpy arrays
     # and rebuild them afterwards if no return_tensors is specified
     # Note that we lose the specific device the tensor may be on for PyTorch

     SCREAMING_SNAKE_CASE__    							=   required_input[0]
     if isinstance(_lowercase ,			(list, tuple)   ):
       # first_element might be an empty list/tuple in some edge cases so we grab the first non empty element.
       SCREAMING_SNAKE_CASE__    							=   0
       while len(required_input[index]   ) == 0:
         index += 1
       if index < len(_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   required_input[index][0]

     if return_tensors is None:
       if is_tf_tensor(_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   """tf"""
       elif is_torch_tensor(_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   """pt"""
       elif isinstance(_lowercase ,			(int, float, list, tuple, np.ndarray)   ):
         SCREAMING_SNAKE_CASE__    							=   """np"""
       else:
         raise ValueError(
             f"""type of {first_element} unknown: {type(_lowercase   )}. """
             """Should be one of a python, numpy, pytorch or tensorflow object."""   )

     for key, value in processed_features.items():
       if isinstance(value[0] ,			(int, float)   ):
         SCREAMING_SNAKE_CASE__    							=   to_numpy(_lowercase   )
       else:
         SCREAMING_SNAKE_CASE__    							=   [to_numpy(_lowercase   ) for v in value]

        # Convert padding_strategy in PaddingStrategy
     SCREAMING_SNAKE_CASE__    							=   self._get_padding_strategies(padding=_lowercase ,			max_length=_lowercase   )

     SCREAMING_SNAKE_CASE__    							=   processed_features[self.model_input_names[0]]

     SCREAMING_SNAKE_CASE__    							=   len(_lowercase   )
     if not all(len(_lowercase   ) == batch_size for v in processed_features.values()   ):
       raise ValueError("""Some items in the output dictionary have a different batch size than others."""   )

     SCREAMING_SNAKE_CASE__    							=   []
     for i in range(_lowercase   ):
       SCREAMING_SNAKE_CASE__    							=   {k: v[i] for k, v in processed_features.items()}
       # truncation
       SCREAMING_SNAKE_CASE__    							=   self._truncate(
           _lowercase ,			max_length=_lowercase ,			pad_to_multiple_of=_lowercase ,			truncation=_lowercase ,			)
       truncated_inputs.append(_lowercase   )

     if padding_strategy == PaddingStrategy.LONGEST:
       # make sure that `max_length` cannot be longer than the longest truncated length
       SCREAMING_SNAKE_CASE__    							=   max(len(input_slice[self.model_input_names[0]]   ) for input_slice in truncated_inputs   )
       SCREAMING_SNAKE_CASE__    							=   PaddingStrategy.MAX_LENGTH

     SCREAMING_SNAKE_CASE__    							=   {}
     for i in range(_lowercase   ):
       # padding
       SCREAMING_SNAKE_CASE__    							=   self._pad(
           truncated_inputs[i] ,			max_length=_lowercase ,			padding_strategy=_lowercase ,			pad_to_multiple_of=_lowercase ,			return_attention_mask=_lowercase ,			)

       for key, value in outputs.items():
         if key not in batch_outputs:
           SCREAMING_SNAKE_CASE__    							=   []
         if value.dtype is np.dtype(np.floataa   ):
           SCREAMING_SNAKE_CASE__    							=   value.astype(np.floataa   )
         batch_outputs[key].append(_lowercase   )

     return BatchFeature(_lowercase ,			tensor_type=_lowercase   )




   def 			__a		(					self    :       List[Any] ,			_lowercase    :       Union[Dict[str, np.ndarray], BatchFeature] ,			_lowercase    :       Optional[int] = None ,			_lowercase    :       PaddingStrategy = PaddingStrategy.DO_NOT_PAD ,			_lowercase    :       Optional[int] = None ,			_lowercase    :       Optional[bool] = None ,			):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__    							=   processed_features[self.model_input_names[0]]

     if padding_strategy == PaddingStrategy.LONGEST:
       SCREAMING_SNAKE_CASE__    							=   len(_lowercase   )

     if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
       SCREAMING_SNAKE_CASE__    							=   ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

     SCREAMING_SNAKE_CASE__    							=   padding_strategy != PaddingStrategy.DO_NOT_PAD and len(_lowercase   ) < max_length

     if return_attention_mask and "attention_mask" not in processed_features:
       SCREAMING_SNAKE_CASE__    							=   np.ones(len(_lowercase   ) ,			dtype=np.intaa   )

     if needs_to_be_padded:
       SCREAMING_SNAKE_CASE__    							=   max_length - len(_lowercase   )
       if self.padding_side == "right":
         if return_attention_mask:
           SCREAMING_SNAKE_CASE__    							=   np.pad(
               processed_features["""attention_mask"""] ,			(0, difference)   )
         SCREAMING_SNAKE_CASE__    							=   ((0, difference), (0, 0)) if self.feature_size > 1 else (0, difference)
         SCREAMING_SNAKE_CASE__    							=   np.pad(
             _lowercase ,			_lowercase ,			"""constant""" ,			constant_values=self.padding_value   )
       elif self.padding_side == "left":
         if return_attention_mask:
           SCREAMING_SNAKE_CASE__    							=   np.pad(
               processed_features["""attention_mask"""] ,			(difference, 0)   )
         SCREAMING_SNAKE_CASE__    							=   ((difference, 0), (0, 0)) if self.feature_size > 1 else (difference, 0)
         SCREAMING_SNAKE_CASE__    							=   np.pad(
             _lowercase ,			_lowercase ,			"""constant""" ,			constant_values=self.padding_value   )
       else:
         raise ValueError("""Invalid padding strategy:""" + str(self.padding_side   )   )

     return processed_features




   def 			__a		(					self    :       List[str] ,			_lowercase    :       Union[Dict[str, np.ndarray], BatchFeature] ,			_lowercase    :       Optional[int] = None ,			_lowercase    :       Optional[int] = None ,			_lowercase    :       Optional[bool] = None ,			):



     """simple docstring"""






     if not truncation:
       return processed_features
     elif truncation and max_length is None:
       raise ValueError("""When setting ``truncation=True``, make sure that ``max_length`` is defined."""   )

     SCREAMING_SNAKE_CASE__    							=   processed_features[self.model_input_names[0]]

     # find `max_length` that fits `pad_to_multiple_of`
     if max_length is not None and pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
       SCREAMING_SNAKE_CASE__    							=   ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of

     SCREAMING_SNAKE_CASE__    							=   len(_lowercase   ) > max_length

     if needs_to_be_truncated:
       SCREAMING_SNAKE_CASE__    							=   processed_features[self.model_input_names[0]][:max_length]
       if "attention_mask" in processed_features:
         SCREAMING_SNAKE_CASE__    							=   processed_features["""attention_mask"""][:max_length]

     return processed_features




   def 			__a		(					self    :       Any ,			_lowercase    :       List[Any]=False ,			_lowercase    :       List[Any]=None   ):



     """simple docstring"""






     if padding is not False:
       if padding is True:
         SCREAMING_SNAKE_CASE__    							=   PaddingStrategy.LONGEST  # Default to pad to the longest sequence in the batch
       elif not isinstance(_lowercase ,			_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   PaddingStrategy(_lowercase   )
       elif isinstance(_lowercase ,			_lowercase   ):
         SCREAMING_SNAKE_CASE__    							=   padding
     else:
       SCREAMING_SNAKE_CASE__    							=   PaddingStrategy.DO_NOT_PAD

     # Set max length if needed
     if max_length is None:
       if padding_strategy == PaddingStrategy.MAX_LENGTH:
         raise ValueError(
             f"""When setting ``padding={PaddingStrategy.MAX_LENGTH}``, make sure that max_length is defined"""   )

        # Test if we have a padding value
     if padding_strategy != PaddingStrategy.DO_NOT_PAD and (self.padding_value is None):
       raise ValueError(
           """Asking to pad but the feature_extractor does not have a padding value. Please select a value to use"""
           """ as `padding_value`. For example: `feature_extractor.padding_value = 0.0`."""   )

     return padding_strategy

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

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

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

from .utils import require_pil







class __snake_case       (		lowerCamelCase_	):




   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






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




   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






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




   def 			__a		(					self    :       int   ):



     """simple docstring"""






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




   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






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




   def 			__a		(					self    :       Optional[Any]   ):



     """simple docstring"""






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




   def 			__a		(					self    :       str   ):



     """simple docstring"""






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




   def 			__a		(					self    :       Any   ):



     """simple docstring"""






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




   def 			__a		(					self    :       Tuple   ):



     """simple docstring"""






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




   def 			__a		(					self    :       Dict   ):



     """simple docstring"""






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




   def 			__a		(					self    :       Optional[int]   ):



     """simple docstring"""






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




   def 			__a		(					self    :       int   ):



     """simple docstring"""






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




   @require_pil
   def 			__a		(					self    :       List[str]   ):



     """simple docstring"""






     import PIL.Image

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





def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Optional[Any]				,  __UpperCamelCase					: int			)							->      str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferReader(__UpperCamelCase			) if isinstance(__UpperCamelCase				,  pa.Buffer			) else pa.memory_map(__UpperCamelCase			)
  SCREAMING_SNAKE_CASE__    							=   pa.ipc.open_stream(__UpperCamelCase			)
  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Union[str, Any]				,  __UpperCamelCase					: int			)							->      List[str]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  SCREAMING_SNAKE_CASE__    							=   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}			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()
  assert num_examples == 2
  assert num_bytes > 0
  if not fields:
    SCREAMING_SNAKE_CASE__    							=   {"""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 			__SCREAMING_SNAKE_CASE						(      )							->      int:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  SCREAMING_SNAKE_CASE__    							=   Features({"""labels""": ClassLabel(names=["""neg""", """pos"""]			)}			)
  with ArrowWriter(stream=__UpperCamelCase				,  features=__UpperCamelCase			) as writer:
    writer.write({"""labels""": 0}			)
    writer.write({"""labels""": 1}			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   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__    							=   pa.BufferReader(output.getvalue()			)
  SCREAMING_SNAKE_CASE__    							=   pa.ipc.open_stream(__UpperCamelCase			)
  SCREAMING_SNAKE_CASE__    							=   f.read_all()
  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: List[str]			)							->      List[str]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   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]			)
      SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()



@pytest.mark.parametrize("""writer_batch_size"""				,  [None, 2, 10]			)
def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Dict			)							->      Dict:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   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			)
      SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()



@pytest.mark.parametrize("""writer_batch_size"""				,  [None, 2, 10]			)
def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: List[str]			)							->      int:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   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			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Optional[int]				,  __UpperCamelCase					: Union[str, Any]			)							->      Optional[int]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  SCREAMING_SNAKE_CASE__    							=   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""": []}			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()
  assert num_examples == 2
  assert num_bytes > 0
  if not fields:
    SCREAMING_SNAKE_CASE__    							=   {"""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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: int				,  __UpperCamelCase					: Union[str, Any]			)							->      Any:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  SCREAMING_SNAKE_CASE__    							=   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]}			)			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()
  assert num_examples == 2
  assert num_bytes > 0
  if not fields:
    SCREAMING_SNAKE_CASE__    							=   {"""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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Union[str, Any]				,  __UpperCamelCase					: List[str]			)							->      str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  SCREAMING_SNAKE_CASE__    							=   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]}			)			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()
  assert num_examples == 2
  assert num_bytes > 0
  if not fields:
    SCREAMING_SNAKE_CASE__    							=   {"""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 			__SCREAMING_SNAKE_CASE						(      )							->      List[Any]:







  """simple docstring"""





  with tempfile.TemporaryDirectory() as tmp_dir:
    SCREAMING_SNAKE_CASE__    							=   {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    SCREAMING_SNAKE_CASE__    							=   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]}			)
      SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: int			)							->      Tuple:







  """simple docstring"""





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



def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Dict				,  __UpperCamelCase					: Union[str, Any]			)							->      Tuple:







  """simple docstring"""





  if isinstance(lst[0]				,  __UpperCamelCase			):
    change_first_primitive_element_in_list(lst[0]				,  __UpperCamelCase			)
  else:
    SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Union[str, Any]				,  __UpperCamelCase					: Optional[int]				,  __UpperCamelCase					: Dict			)							->      Any:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: List[Any]				,  __UpperCamelCase					: Dict				,  __UpperCamelCase					: List[str]			)							->      Optional[int]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   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
    SCREAMING_SNAKE_CASE__    							=   copy.deepcopy(__UpperCamelCase			)
    SCREAMING_SNAKE_CASE__    							=   np.iinfo(expected_dtype.to_pandas_dtype()			).max + 1
    change_first_primitive_element_in_list(__UpperCamelCase				,  __UpperCamelCase			)
    SCREAMING_SNAKE_CASE__    							=   pa.array(OptimizedTypedSequence(__UpperCamelCase				,  col=__UpperCamelCase			)			)
    assert get_base_dtype(arr.type			) == pa.intaa()



@pytest.mark.parametrize("""raise_exception"""				,  [False, True]			)
def 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Optional[int]				,  __UpperCamelCase					: Union[str, Any]			)							->      str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Tuple			)							->      str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   """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}			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()
  assert num_examples == 2
  assert num_bytes > 0
  assert mockfs.exists(__UpperCamelCase			)



def 			__SCREAMING_SNAKE_CASE						(      )							->      str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  with ParquetWriter(stream=__UpperCamelCase			) as writer:
    writer.write({"""col_1""": """foo""", """col_2""": 1}			)
    writer.write({"""col_1""": """bar""", """col_2""": 2}			)
    SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__    							=   writer.finalize()
  assert num_examples == 2
  assert num_bytes > 0
  SCREAMING_SNAKE_CASE__    							=   pa.BufferReader(output.getvalue()			)
  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      __UpperCamelCase					: Tuple				,  __UpperCamelCase					: Tuple			)							->      Optional[Any]:







  """simple docstring"""





  import PIL.Image

  SCREAMING_SNAKE_CASE__    							=   str(tmp_path / """test_image_rgb.jpg"""			)
  PIL.Image.fromarray(np.zeros((5, 5)				,  dtype=np.uinta			)			).save(__UpperCamelCase				,  format="""png"""			)
  SCREAMING_SNAKE_CASE__    							=   pa.BufferOutputStream()
  with ParquetWriter(
      stream=__UpperCamelCase				,  features=Features({"""image""": Image()}			)				,  embed_local_files=__UpperCamelCase			) as writer:
    writer.write({"""image""": image_path}			)
    writer.finalize()
  SCREAMING_SNAKE_CASE__    							=   pa.BufferReader(output.getvalue()			)
  SCREAMING_SNAKE_CASE__    							=   pq.read_table(__UpperCamelCase			)
  SCREAMING_SNAKE_CASE__    							=   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 			__SCREAMING_SNAKE_CASE						(      )							->      List[Any]:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__    							=   pa.schema([pa.field("""col_1"""				,  pa.string()				,  nullable=__UpperCamelCase			)]			)
  SCREAMING_SNAKE_CASE__    							=   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()			)]			)
