





import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


_snake_case    :       str		       =    logging.get_logger(__name__)

_snake_case    :       Tuple		       =    list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
_snake_case    :       Union[str, Any]		       =    tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)



@dataclass
class 							_UpperCAmelCase       :

  """simple docstring"""


  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """Model type selected in the list: """ + """, """.join(_UpperCamelCase       )}       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""}       )
  a_              =					field(
      default=1_28						,       metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }						,       )
  a_              =					field(
      default=1_28						,       metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""}						,       )
  a_              =					field(
      default=64						,       metadata={
          """help""": (
              """The maximum number of tokens for the question. Questions longer than this will """
              """be truncated to this length."""
          )
      }						,       )
  a_              =					field(
      default=30						,       metadata={
          """help""": (
              """The maximum length of an answer that can be generated. This is needed because the start """
              """and end predictions are not conditioned on one another."""
          )
      }						,       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """Overwrite the cached training and evaluation sets"""}       )
  a_              =					field(
      default=_UpperCamelCase						,       metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""}       )
  a_              =					field(
      default=0.0						,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  a_              =					field(
      default=20						,       metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""}       )
  a_              =					field(
      default=0						,       metadata={
          """help""": (
              """language id of input for language-specific xlm models (see"""
              """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)"""
          )
      }						,       )
  a_              =					field(default=1						,       metadata={"""help""": """multiple threads for converting example to features"""}       )





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					"""train"""
  a_              =					"""dev"""





class 							_UpperCAmelCase       (       _UpperCamelCase       ):

  """simple docstring"""


  a_              =					42
  a_              =					42
  a_              =					42
  a_              =					42






  def __init__(							self					:						int   ,    lowerCAmelCase_					:						SquadDataTrainingArguments   ,    lowerCAmelCase_					:						PreTrainedTokenizer   ,    lowerCAmelCase_					:						Optional[int] = None   ,    lowerCAmelCase_					:						Union[str, Split] = Split.train   ,    lowerCAmelCase_					:						Optional[bool] = False   ,    lowerCAmelCase_					:						Optional[str] = None   ,    lowerCAmelCase_					:						Optional[str] = "pt"   ,    )				->		Tuple:
     __lowerCAmelCase				      =      args
     __lowerCAmelCase				      =      is_language_sensitive
     __lowerCAmelCase				      =      SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
     if isinstance(lowerCAmelCase_   ,    lowerCAmelCase_	):
        try:
           __lowerCAmelCase				      =      Split[mode]
        except KeyError:
           raise KeyError('mode is not a valid split name'	)
     __lowerCAmelCase				      =      mode
     # Load data features from cache or dataset file
     __lowerCAmelCase				      =      'v2' if args.version_2_with_negative else 'v1'
     __lowerCAmelCase				      =      os.path.join(
         cache_dir if cache_dir is not None else args.data_dir   ,    f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}"""   ,    )

     # Make sure only the first process in distributed training processes the dataset,
     # and the others will use the cache.
     __lowerCAmelCase				      =      cached_features_file + '.lock'
     with FileLock(lowerCAmelCase_	):
        if os.path.exists(lowerCAmelCase_	) and not args.overwrite_cache:
           __lowerCAmelCase				      =      time.time()
           __lowerCAmelCase				      =      torch.load(lowerCAmelCase_	)

           # Legacy cache files have only features, while new cache files
           # will have dataset and examples also.
           __lowerCAmelCase				      =      self.old_features['features']
           __lowerCAmelCase				      =      self.old_features.get('dataset'   ,    lowerCAmelCase_	)
           __lowerCAmelCase				      =      self.old_features.get('examples'   ,    lowerCAmelCase_	)
           logger.info(
               f"""Loading features from cached file {cached_features_file} [took %.3f s]"""   ,    time.time() - start	)

           if self.dataset is None or self.examples is None:
              logger.warning(
                  f"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in"""
                  ' future run'	)
        else:
           if mode == Split.dev:
              __lowerCAmelCase				      =      self.processor.get_dev_examples(args.data_dir	)
           else:
              __lowerCAmelCase				      =      self.processor.get_train_examples(args.data_dir	)

           __lowerCAmelCase      ,      __lowerCAmelCase				      =      squad_convert_examples_to_features(
               examples=self.examples   ,    tokenizer=lowerCAmelCase_   ,    max_seq_length=args.max_seq_length   ,    doc_stride=args.doc_stride   ,    max_query_length=args.max_query_length   ,    is_training=mode == Split.train   ,    threads=args.threads   ,    return_dataset=lowerCAmelCase_   ,    )

           __lowerCAmelCase				      =      time.time()
           torch.save(
               {'features': self.features, 'dataset': self.dataset, 'examples': self.examples}   ,    lowerCAmelCase_   ,    )
           # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
           logger.info(
               f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]"""	)






  def __len__(							self					:						Tuple	)				->		List[str]:
     return len(self.features	)






  def __getitem__(							self					:						Dict   ,    lowerCAmelCase_					:						Optional[int]	)				->		Dict[str, torch.Tensor]:
     # Convert to Tensors and build dataset
     __lowerCAmelCase				      =      self.features[i]

     __lowerCAmelCase				      =      torch.tensor(feature.input_ids   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.attention_mask   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.token_type_ids   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.cls_index   ,    dtype=torch.long	)
     __lowerCAmelCase				      =      torch.tensor(feature.p_mask   ,    dtype=torch.float	)
     __lowerCAmelCase				      =      torch.tensor(feature.is_impossible   ,    dtype=torch.float	)

     __lowerCAmelCase				      =      {
         'input_ids': input_ids,
         'attention_mask': attention_mask,
         'token_type_ids': token_type_ids,
     }

     if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
        del inputs["token_type_ids"]

     if self.args.model_type in ["xlnet", "xlm"]:
        inputs.update({'cls_index': cls_index, 'p_mask': p_mask}	)
        if self.args.version_2_with_negative:
           inputs.update({'is_impossible': is_impossible}	)
        if self.is_language_sensitive:
           inputs.update({'langs': (torch.ones(input_ids.shape   ,    dtype=torch.intaa	) * self.args.lang_id)}	)

     if self.mode == Split.train:
        __lowerCAmelCase				      =      torch.tensor(feature.start_position   ,    dtype=torch.long	)
        __lowerCAmelCase				      =      torch.tensor(feature.end_position   ,    dtype=torch.long	)
        inputs.update({'start_positions': start_positions, 'end_positions': end_positions}	)

     return inputs



"""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_    (			_UpperCAmelCase						):







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






        '''simple docstring'''






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







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






        '''simple docstring'''






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







    def   _snake_case       (      self      :							Tuple  )		->int:






        '''simple docstring'''






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







    def   _snake_case       (      self      :							Optional[Any]  )		->Tuple:






        '''simple docstring'''






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







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






        '''simple docstring'''






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







    def   _snake_case       (      self      :							int  )		->Tuple:






        '''simple docstring'''






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







    def   _snake_case       (      self      :							Dict  )		->str:






        '''simple docstring'''






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







    def   _snake_case       (      self      :							Union[str, Any]  )		->Optional[int]:






        '''simple docstring'''






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







    def   _snake_case       (      self      :							Tuple  )		->Any:






        '''simple docstring'''






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







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






        '''simple docstring'''






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







    def   _snake_case       (      self      :							Any  )		->Dict:






        '''simple docstring'''






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







    @require_pil
    def   _snake_case       (      self      :							Optional[Any]  )		->Tuple:






        '''simple docstring'''






        import PIL.Image

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







def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Dict:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferReader(_A   ) if isinstance(_A       ,   pa.Buffer   ) else pa.memory_map(_A   )
    _UpperCAmelCase        = pa.ipc.open_stream(_A   )
    _UpperCAmelCase        = f.read_all()
    assert len(pa_table.to_batches()   ) == expected_num_chunks
    assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
    del pa_table


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Any:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write({"""col_1""": """foo""", """col_2""": 1}   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


def 			_UpperCamelCase						(    )     ->	Dict:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = Features({"""labels""": ClassLabel(names=["""neg""", """pos"""]   )}   )
    with ArrowWriter(stream=_A       ,   features=_A   ) as writer:
        writer.write({"""labels""": 0}   )
        writer.write({"""labels""": 1}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    assert writer._schema == features.arrow_schema
    assert writer._schema.metadata == features.arrow_schema.metadata
    _UpperCAmelCase        = pa.BufferReader(output.getvalue()   )
    _UpperCAmelCase        = pa.ipc.open_stream(_A   )
    _UpperCAmelCase        = f.read_all()
    _UpperCAmelCase        = 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(_A   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
def 			_UpperCamelCase						(    _A   )     ->	int:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(
        stream=_A       ,   writer_batch_size=_A       ,   hash_salt="""split_name"""       ,   check_duplicates=_A       ,   ) as writer:
        with pytest.raises(_A   ):
            writer.write({"""col_1""": """foo""", """col_2""": 1}       ,   key=[1, 2]   )
            _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 2, 1_0]   )
def 			_UpperCamelCase						(    _A   )     ->	List[Any]:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(
        stream=_A       ,   writer_batch_size=_A       ,   hash_salt="""split_name"""       ,   check_duplicates=_A       ,   ) as writer:
        with pytest.raises(_A   ):
            writer.write({"""col_1""": """foo""", """col_2""": 1}       ,   key=1_0   )
            writer.write({"""col_1""": """bar""", """col_2""": 2}       ,   key=1_0   )
            _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 2, 1_0]   )
def 			_UpperCamelCase						(    _A   )     ->	Dict:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ArrowWriter(
        stream=_A       ,   writer_batch_size=_A       ,   hash_salt="""split_name"""       ,   check_duplicates=_A       ,   ) as writer:
        writer.write({"""col_1""": """foo""", """col_2""": 1}       ,   key=1   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}       ,   key=2   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Any:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}   )
        writer.write_batch({"""col_1""": [], """col_2""": []}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	str:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) as writer:
        writer.write_table(pa.Table.from_pydict({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}   )   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


@pytest.mark.parametrize("""writer_batch_size"""       ,   [None, 1, 1_0]   )
@pytest.mark.parametrize(
    """fields"""       ,   [None, {"""col_1""": pa.string(), """col_2""": pa.intaa()}, {"""col_1""": pa.string(), """col_2""": pa.intaa()}]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	int:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    _UpperCAmelCase        = pa.schema(_A   ) if fields else None
    with ArrowWriter(stream=_A       ,   schema=_A       ,   writer_batch_size=_A   ) 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]}   )   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    if not fields:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
    assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
    _check_output(output.getvalue()       ,   expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )


def 			_UpperCamelCase						(    )     ->	Dict:





    """simple docstring"""

    with tempfile.TemporaryDirectory() as tmp_dir:
        _UpperCAmelCase        = {"""col_1""": pa.string(), """col_2""": pa.intaa()}
        _UpperCAmelCase        = os.path.join(_A       ,   """test.arrow"""   )
        with ArrowWriter(path=_A       ,   schema=pa.schema(_A   )   ) as writer:
            writer.write_batch({"""col_1""": ["""foo""", """bar"""], """col_2""": [1, 2]}   )
            _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
        assert num_examples == 2
        assert num_bytes > 0
        assert writer._schema == pa.schema(_A       ,   metadata=writer._schema.metadata   )
        _check_output(_A       ,   1   )


def 			_UpperCamelCase						(    _A   )     ->	Optional[int]:





    """simple docstring"""

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


def 			_UpperCamelCase						(    _A       ,   _A   )     ->	str:





    """simple docstring"""

    if isinstance(lst[0]       ,   _A   ):
        change_first_primitive_element_in_list(lst[0]       ,   _A   )
    else:
        _UpperCAmelCase        = 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 			_UpperCamelCase						(    _A       ,   _A       ,   _A   )     ->	Optional[int]:





    """simple docstring"""

    _UpperCAmelCase        = pa.array(TypedSequence(_A       ,   optimized_int_type=_A   )   )
    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 			_UpperCamelCase						(    _A       ,   _A       ,   _A   )     ->	Any:





    """simple docstring"""

    _UpperCAmelCase        = pa.array(OptimizedTypedSequence(_A       ,   col=_A   )   )
    assert get_base_dtype(arr.type   ) == expected_dtype

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


@pytest.mark.parametrize("""raise_exception"""       ,   [False, True]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Optional[Any]:





    """simple docstring"""

    _UpperCAmelCase        = str(tmp_path / """dataset-train.arrow"""   )
    try:
        with ArrowWriter(path=_A   ) as writer:
            if raise_exception:
                raise pa.lib.ArrowInvalid()
            else:
                writer.stream.close()
    except pa.lib.ArrowInvalid:
        pass
    finally:
        assert writer.stream.closed


def 			_UpperCamelCase						(    _A   )     ->	List[str]:





    """simple docstring"""

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


def 			_UpperCamelCase						(    )     ->	List[Any]:





    """simple docstring"""

    _UpperCAmelCase        = pa.BufferOutputStream()
    with ParquetWriter(stream=_A   ) as writer:
        writer.write({"""col_1""": """foo""", """col_2""": 1}   )
        writer.write({"""col_1""": """bar""", """col_2""": 2}   )
        _UpperCAmelCase     ,_UpperCAmelCase        = writer.finalize()
    assert num_examples == 2
    assert num_bytes > 0
    _UpperCAmelCase        = pa.BufferReader(output.getvalue()   )
    _UpperCAmelCase        = pq.read_table(_A   )
    assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}


@require_pil
@pytest.mark.parametrize("""embed_local_files"""       ,   [False, True]   )
def 			_UpperCamelCase						(    _A       ,   _A   )     ->	Union[str, Any]:





    """simple docstring"""

    import PIL.Image

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





    """simple docstring"""

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