



'''simple docstring'''


import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


snake_case__					:      Dict				      =  logging.get_logger(__name__)

snake_case__					:      Any				      =  '''▁'''

snake_case__					:      Union[str, Any]				      =  {'''vocab_file''': '''vocab.txt''', '''sentencepiece_model_ckpt''': '''sentencepiece.bpe.model'''}

snake_case__					:      Optional[Any]				      =  {
    '''sentencepiece_model_file''': '''sentencepiece.bpe.model''',
    '''vocab_file''': '''vocab.txt''',
}

snake_case__					:      Union[str, Any]				      =  {
    '''vocab_file''': {
        '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''',
        '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt''',
    },
    '''sentencepiece_model_file''': {
        '''ernie-m-base''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''',
        '''ernie-m-large''': '''https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model''',
    },
}

snake_case__					:      int				      =  {
    '''ernie-m-base''': 514,
    '''ernie-m-large''': 514,
}

snake_case__					:      List[Any]				      =  {
    '''ernie-m-base''': {'''do_lower_case''': False},
    '''ernie-m-large''': {'''do_lower_case''': False},
}






class 					__SCREAMING_SNAKE_CASE						(	snake_case__	):







  '''simple docstring'''






  lowerCamelCase_		:List[str]						   =		["input_ids"]

  lowerCamelCase_		:List[Any]						   =		VOCAB_FILES_NAMES
  lowerCamelCase_		:Union[str, Any]						   =		PRETRAINED_INIT_CONFIGURATION
  lowerCamelCase_		:Optional[Any]						   =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  lowerCamelCase_		:Tuple						   =		PRETRAINED_VOCAB_FILES_MAP
  lowerCamelCase_		:Any						   =		RESOURCE_FILES_NAMES


  def __init__(			self				,		snake_case_				,		snake_case_=None				,		snake_case_=False				,		snake_case_="utf8"				,		snake_case_="[UNK]"				,		snake_case_="[SEP]"				,		snake_case_="[PAD]"				,		snake_case_="[CLS]"				,		snake_case_="[MASK]"				,		snake_case_ = None				,		**snake_case_				,		):




       '''simple docstring'''

       UpperCAmelCase_							:       Tuple       =				{} if sp_model_kwargs is None else sp_model_kwargs
       super().__init__(
           do_lower_case=_A				,		unk_token=_A				,		sep_token=_A				,		pad_token=_A				,		cls_token=_A				,		mask_token=_A				,		vocab_file=_A				,		encoding=_A				,		sp_model_kwargs=self.sp_model_kwargs				,		**_A				,		)
       UpperCAmelCase_							:       List[Any]       =				do_lower_case
       UpperCAmelCase_							:       List[str]       =				sentencepiece_model_ckpt
       UpperCAmelCase_							:       Optional[int]       =				spm.SentencePieceProcessor(**self.sp_model_kwargs						)
       self.sp_model.Load(_A						)

       # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
       if vocab_file is not None:
            UpperCAmelCase_							:       Tuple       =				self.load_vocab(filepath=_A						)
       else:
            UpperCAmelCase_							:       Optional[int]       =				{self.sp_model.id_to_piece(_A						): id for id in range(self.sp_model.get_piece_size()						)}
       UpperCAmelCase_							:       Tuple       =				{v: k for k, v in self.vocab.items()}


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       if text is None:
            return None

       UpperCAmelCase_							:       Any       =				self.tokenize(_A						)
       UpperCAmelCase_       ,      UpperCAmelCase_							:       str       =				'', []

       for i, ch in enumerate(_A						):
            if ch in self.SP_CHAR_MAPPING:
                 UpperCAmelCase_							:       str       =				self.SP_CHAR_MAPPING.get(_A						)
            else:
                 UpperCAmelCase_							:       str       =				unicodedata.normalize('NFKC'				,		_A						)
            if self.is_whitespace(_A						):
                 continue
            normalized_text += ch
            char_mapping.extend([i] * len(_A						)						)

       UpperCAmelCase_       ,      UpperCAmelCase_       ,      UpperCAmelCase_							:       Dict       =				normalized_text, [], 0

       if self.do_lower_case:
            UpperCAmelCase_							:       Any       =				text.lower()

       for token in split_tokens:
            if token[:1] == "▁":
                 UpperCAmelCase_							:       int       =				token[1:]
            UpperCAmelCase_							:       Optional[int]       =				text[offset:].index(_A						) + offset
            UpperCAmelCase_							:       Optional[Any]       =				start + len(_A						)

            token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)						)
            UpperCAmelCase_							:       Union[str, Any]       =				end
       return token_mapping


  @property
  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       return len(self.vocab						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def __getstate__(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[str]       =				self.__dict__.copy()
       UpperCAmelCase_							:       Dict       =				None
       return state


  def __setstate__(			self				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       Union[str, Any]       =				d

       # for backward compatibility
       if not hasattr(self				,		'sp_model_kwargs'						):
            UpperCAmelCase_							:       Optional[Any]       =				{}

       UpperCAmelCase_							:       Any       =				spm.SentencePieceProcessor(**self.sp_model_kwargs						)
       self.sp_model.Load(self.sentencepiece_model_ckpt						)


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       return "".join((self.SP_CHAR_MAPPING.get(_A				,		_A						) for c in text)						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_=False				,		snake_case_=6_4				,		snake_case_=0.1						):




       '''simple docstring'''

       if self.sp_model_kwargs.get('enable_sampling'						) is True:
            UpperCAmelCase_							:       Optional[int]       =				True
       if self.sp_model_kwargs.get('alpha'						) is not None:
            UpperCAmelCase_							:       int       =				self.sp_model_kwargs.get('alpha'						)
       if self.sp_model_kwargs.get('nbest_size'						) is not None:
            UpperCAmelCase_							:       List[Any]       =				self.sp_model_kwargs.get('nbest_size'						)

       if not enable_sampling:
            UpperCAmelCase_							:       List[str]       =				self.sp_model.EncodeAsPieces(_A						)
       else:
            UpperCAmelCase_							:       Optional[int]       =				self.sp_model.SampleEncodeAsPieces(_A				,		_A				,		_A						)
       UpperCAmelCase_							:       List[str]       =				[]
       for pi, piece in enumerate(_A						):
            if piece == SPIECE_UNDERLINE:
                 if not pieces[pi + 1].startswith(_A						) and pi != 0:
                      new_pieces.append(_A						)
                      continue
                 else:
                      continue
            UpperCAmelCase_							:       int       =				0
            for i, chunk in enumerate(_A						):
                 if chunk == SPIECE_UNDERLINE:
                      continue
                 if self.is_ch_char(_A						) or self.is_punct(_A						):
                      if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                           new_pieces.append(piece[lst_i:i]						)
                      new_pieces.append(_A						)
                      UpperCAmelCase_							:       int       =				i + 1
                 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
                      if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                           new_pieces.append(piece[lst_i:i]						)
                      UpperCAmelCase_							:       List[str]       =				i
                 elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
                      if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                           new_pieces.append(piece[lst_i:i]						)
                      UpperCAmelCase_							:       Optional[int]       =				i
            if len(_A						) > lst_i:
                 new_pieces.append(piece[lst_i:]						)
       return new_pieces


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       Any       =				''.join(_A						).replace(_A				,		' '						).strip()
       return out_string


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       str       =				self.convert_ids_to_tokens(_A						)
       UpperCAmelCase_							:       Union[str, Any]       =				''.join(_A						).replace(_A				,		' '						).strip()
       return out_string


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       return self.vocab.get(_A				,		self.vocab.get(self.unk_token						)						)


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       return self.reverse_vocab.get(_A				,		self.unk_token						)


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_=None						):




       '''simple docstring'''

       if token_ids_a is None:
            return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
       UpperCAmelCase_							:       int       =				[self.cls_token_id]
       UpperCAmelCase_							:       List[Any]       =				[self.sep_token_id]
       return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_=None						):




       '''simple docstring'''

       if offset_mapping_a is None:
            return [(0, 0)] + offset_mapping_a + [(0, 0)]

       return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_=None				,		snake_case_=False						):




       '''simple docstring'''

       if already_has_special_tokens:
            if token_ids_a is not None:
                 raise ValueError(
                     'You should not supply a second sequence if the provided sequence of '
                     'ids is already formatted with special tokens for the model.'						)
            return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

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


  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_ = None						):




       '''simple docstring'''

       if token_ids_a is None:
            # [CLS] X [SEP]
            return (len(_A						) + 2) * [0]

       # [CLS] A [SEP] [SEP] B [SEP]
       return [0] * (len(_A						) + 1) + [1] * (len(_A						) + 3)


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       if "\u4e00" <= char <= "\u9fff":
            return True
       return False


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       if ("a" <= char <= "z") or ("A" <= char <= "Z"):
            return True
       return False


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       if char in ",;:.?!~，；：。？！《》【】":
            return True
       return False


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       if char == " " or char == "\t" or char == "\n" or char == "\r":
            return True
       if len(_A						) == 1:
            UpperCAmelCase_							:       List[str]       =				unicodedata.category(_A						)
            if cat == "Zs":
                 return True
       return False


  def _UpperCamelCase					(			self				,		snake_case_						):




       '''simple docstring'''

       UpperCAmelCase_							:       int       =				{}
       with io.open(_A				,		'r'				,		encoding='utf-8'						) as f:
            for index, line in enumerate(_A						):
                 UpperCAmelCase_							:       Optional[int]       =				line.rstrip('\n'						)
                 UpperCAmelCase_							:       Optional[Any]       =				int(_A						)

       return token_to_idx






  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_ = None						):




       '''simple docstring'''

       UpperCAmelCase_							:       List[Any]       =				0
       if os.path.isdir(_A						):
            UpperCAmelCase_							:       Tuple       =				os.path.join(
                _A				,		(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']						)
       else:
            UpperCAmelCase_							:       List[Any]       =				(filename_prefix + '-' if filename_prefix else '') + save_directory
       with open(_A				,		'w'				,		encoding='utf-8'						) as writer:
            for token, token_index in sorted(self.vocab.items()				,		key=lambda snake_case_						: kv[1]						):
                 if index != token_index:
                      logger.warning(
                          F'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
                          ' Please check that the vocabulary is not corrupted!'						)
                      UpperCAmelCase_							:       Any       =				token_index
                 writer.write(token + '\n'						)
                 index += 1

       UpperCAmelCase_							:       Union[str, Any]       =				os.path.join(_A				,		'sentencepiece.bpe.model'						)
       with open(_A				,		'wb'						) as fi:
            UpperCAmelCase_							:       Tuple       =				self.sp_model.serialized_model_proto()
            fi.write(_A						)

       return (vocab_file,)







'''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 					__SCREAMING_SNAKE_CASE						(	lowerCamelCase_	):







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       with self.assertRaises(snake_case_						):
            UpperCAmelCase_							:       Optional[int]       =				pa.array(TypedSequence([1, 2, 3]						)				,		type=pa.intaa()						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       with self.assertRaises(snake_case_						):
            UpperCAmelCase_							:       List[Any]       =				pa.array(TypedSequence([1, 2, 3]				,		try_type=Value('bool'						)				,		type=Value('int64'						)						)						)


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

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


  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       UpperCAmelCase_							:       Union[str, Any]       =				pa.array(TypedSequence(['foo', 'bar']				,		try_type=ArrayaD((1, 3)				,		'int64'						)						)						)
       self.assertEqual(arr.type				,		pa.string()						)






  @require_pil
  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       import PIL.Image

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







def  _lowerCamelCase   (				lowerCamelCase_ :							Any     ,					lowerCamelCase_ :							int       ):



     """simple docstring"""





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


@pytest.mark.parametrize('writer_batch_size'     ,					[None, 1, 10]       )
@pytest.mark.parametrize(
    'fields'     ,					[None, {'col_1': pa.string(), 'col_2': pa.intaa()}, {'col_1': pa.string(), 'col_2': pa.intaa()}]       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							int       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				pa.BufferOutputStream()
     UpperCAmelCase_							:       Dict       =				pa.schema(lowerCamelCase_       ) if fields else None
     with ArrowWriter(stream=lowerCamelCase_     ,					schema=lowerCamelCase_     ,					writer_batch_size=lowerCamelCase_       ) as writer:
          writer.write({'col_1': 'foo', 'col_2': 1}       )
          writer.write({'col_1': 'bar', 'col_2': 2}       )
          UpperCAmelCase_       ,      UpperCAmelCase_							:       Dict       =				writer.finalize()
     assert num_examples == 2
     assert num_bytes > 0
     if not fields:
          UpperCAmelCase_							:       Optional[int]       =				{'col_1': pa.string(), 'col_2': pa.intaa()}
     assert writer._schema == pa.schema(lowerCamelCase_     ,					metadata=writer._schema.metadata       )
     _check_output(output.getvalue()     ,					expected_num_chunks=num_examples if writer_batch_size == 1 else 1       )


def  _lowerCamelCase   (				):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				pa.BufferOutputStream()
     UpperCAmelCase_							:       Optional[int]       =				Features({'labels': ClassLabel(names=['neg', 'pos']       )}       )
     with ArrowWriter(stream=lowerCamelCase_     ,					features=lowerCamelCase_       ) as writer:
          writer.write({'labels': 0}       )
          writer.write({'labels': 1}       )
          UpperCAmelCase_       ,      UpperCAmelCase_							:       List[Any]       =				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_							:       Any       =				pa.BufferReader(output.getvalue()       )
     UpperCAmelCase_							:       List[str]       =				pa.ipc.open_stream(lowerCamelCase_       )
     UpperCAmelCase_							:       pa.Table       =				f.read_all()
     UpperCAmelCase_							:       Optional[Any]       =				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(lowerCamelCase_       )


@pytest.mark.parametrize('writer_batch_size'     ,					[None, 1, 10]       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Union[str, Any]       =				pa.BufferOutputStream()
     with ArrowWriter(
         stream=lowerCamelCase_     ,					writer_batch_size=lowerCamelCase_     ,					hash_salt='split_name'     ,					check_duplicates=lowerCamelCase_     ,					) as writer:
          with pytest.raises(lowerCamelCase_       ):
               writer.write({'col_1': 'foo', 'col_2': 1}     ,					key=[1, 2]       )
               UpperCAmelCase_       ,      UpperCAmelCase_							:       Any       =				writer.finalize()


@pytest.mark.parametrize('writer_batch_size'     ,					[None, 2, 10]       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       int       =				pa.BufferOutputStream()
     with ArrowWriter(
         stream=lowerCamelCase_     ,					writer_batch_size=lowerCamelCase_     ,					hash_salt='split_name'     ,					check_duplicates=lowerCamelCase_     ,					) as writer:
          with pytest.raises(lowerCamelCase_       ):
               writer.write({'col_1': 'foo', 'col_2': 1}     ,					key=10       )
               writer.write({'col_1': 'bar', 'col_2': 2}     ,					key=10       )
               UpperCAmelCase_       ,      UpperCAmelCase_							:       Optional[Any]       =				writer.finalize()


@pytest.mark.parametrize('writer_batch_size'     ,					[None, 2, 10]       )
def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[int]       ):



     """simple docstring"""





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



     """simple docstring"""





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



     """simple docstring"""





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



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				pa.BufferOutputStream()
     UpperCAmelCase_							:       Tuple       =				pa.schema(lowerCamelCase_       ) if fields else None
     with ArrowWriter(stream=lowerCamelCase_     ,					schema=lowerCamelCase_     ,					writer_batch_size=lowerCamelCase_       ) 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_							:       Optional[int]       =				writer.finalize()
     assert num_examples == 2
     assert num_bytes > 0
     if not fields:
          UpperCAmelCase_							:       Union[str, Any]       =				{'col_1': pa.string(), 'col_2': pa.intaa()}
     assert writer._schema == pa.schema(lowerCamelCase_     ,					metadata=writer._schema.metadata       )
     _check_output(output.getvalue()     ,					expected_num_chunks=num_examples if writer_batch_size == 1 else 1       )


def  _lowerCamelCase   (				):



     """simple docstring"""





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


def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]       ):



     """simple docstring"""





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


def  _lowerCamelCase   (				lowerCamelCase_ :							Optional[int]     ,					lowerCamelCase_ :							Optional[Any]       ):



     """simple docstring"""





     if isinstance(lst[0]     ,					lowerCamelCase_       ):
          change_first_primitive_element_in_list(lst[0]     ,					lowerCamelCase_       )
     else:
          UpperCAmelCase_							:       str       =				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  _lowerCamelCase   (				lowerCamelCase_ :							int     ,					lowerCamelCase_ :							Dict     ,					lowerCamelCase_ :							int       ):



     """simple docstring"""





     UpperCAmelCase_							:       List[Any]       =				pa.array(TypedSequence(lowerCamelCase_     ,					optimized_int_type=lowerCamelCase_       )       )
     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  _lowerCamelCase   (				lowerCamelCase_ :							Optional[Any]     ,					lowerCamelCase_ :							Tuple     ,					lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





     UpperCAmelCase_							:       Tuple       =				pa.array(OptimizedTypedSequence(lowerCamelCase_     ,					col=lowerCamelCase_       )       )
     assert get_base_dtype(arr.type       ) == expected_dtype

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


@pytest.mark.parametrize('raise_exception'     ,					[False, True]       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[str]     ,					lowerCamelCase_ :							List[Any]       ):



     """simple docstring"""





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


def  _lowerCamelCase   (				lowerCamelCase_ :							Dict       ):



     """simple docstring"""





     UpperCAmelCase_							:       Dict       =				'mock://dataset-train.arrow'
     with ArrowWriter(path=lowerCamelCase_     ,					storage_options=mockfs.storage_options       ) as writer:
          assert isinstance(writer._fs     ,					type(lowerCamelCase_       )       )
          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_							:       Tuple       =				writer.finalize()
     assert num_examples == 2
     assert num_bytes > 0
     assert mockfs.exists(lowerCamelCase_       )


def  _lowerCamelCase   (				):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[Any]       =				pa.BufferOutputStream()
     with ParquetWriter(stream=lowerCamelCase_       ) as writer:
          writer.write({'col_1': 'foo', 'col_2': 1}       )
          writer.write({'col_1': 'bar', 'col_2': 2}       )
          UpperCAmelCase_       ,      UpperCAmelCase_							:       Optional[int]       =				writer.finalize()
     assert num_examples == 2
     assert num_bytes > 0
     UpperCAmelCase_							:       List[str]       =				pa.BufferReader(output.getvalue()       )
     UpperCAmelCase_							:       pa.Table       =				pq.read_table(lowerCamelCase_       )
     assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}


@require_pil
@pytest.mark.parametrize('embed_local_files'     ,					[False, True]       )
def  _lowerCamelCase   (				lowerCamelCase_ :							List[Any]     ,					lowerCamelCase_ :							Union[str, Any]       ):



     """simple docstring"""





     import PIL.Image

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



     """simple docstring"""





     UpperCAmelCase_							:       List[str]       =				pa.schema([pa.field('col_1'     ,					pa.string()     ,					nullable=lowerCamelCase_       )]       )
     UpperCAmelCase_							:       Dict       =				pa.BufferOutputStream()
     with ArrowWriter(stream=lowerCamelCase_       ) as writer:
          writer._build_writer(inferred_schema=lowerCamelCase_       )
          assert writer._schema == pa.schema([pa.field('col_1'     ,					pa.string()       )]       )






