




'''simple docstring'''


import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

from filelock import FileLock

from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available


_snake_case   :   Dict     							=	logging.getLogger(__name__)

@dataclass
class     A					:
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       42



@dataclass
class     A					:
							lowercase_           =       42
							lowercase_           =       42
							lowercase_           =       None
							lowercase_           =       None



class     A					(	_a					):
							lowercase_           =       'train'
							lowercase_           =       'dev'
							lowercase_           =       'test'



class     A					:







							@staticmethod
							def      __lowerCAmelCase    (						lowerCAmelCase_ :						Any							,    lowerCAmelCase_ :						Union[Split, str]      )    ->							List[InputExample]:


														"""simple docstring"""


														raise NotImplementedError







							@staticmethod
							def      __lowerCAmelCase    (						lowerCAmelCase_ :						str      )    ->							List[str]:


														"""simple docstring"""


														raise NotImplementedError







							@staticmethod
							def      __lowerCAmelCase    (						lowerCAmelCase_ :						List[InputExample]							,    lowerCAmelCase_ :						List[str]							,    lowerCAmelCase_ :						int							,    lowerCAmelCase_ :						PreTrainedTokenizer							,    lowerCAmelCase_ :						Optional[Any]=False							,    lowerCAmelCase_ :						Optional[Any]="[CLS]"							,    lowerCAmelCase_ :						List[Any]=1							,    lowerCAmelCase_ :						List[str]="[SEP]"							,    lowerCAmelCase_ :						Any=False							,    lowerCAmelCase_ :						Union[str, Any]=False							,    lowerCAmelCase_ :						Optional[Any]=0							,    lowerCAmelCase_ :						Optional[Any]=0							,    lowerCAmelCase_ :						Optional[Any]=-1_00							,    lowerCAmelCase_ :						Any=0							,    lowerCAmelCase_ :						Any=True							,    )    ->							List[InputFeatures]:


														"""simple docstring"""


														_a			  =       {label: i for i, label in enumerate(lowerCAmelCase_      )}

														_a			  =       []
														for ex_index, example in enumerate(lowerCAmelCase_      ):
																					if ex_index % 1_00_00 == 0:
																												logger.info('''Writing example %d of %d'''							,    lowerCAmelCase_							,    len(lowerCAmelCase_      )      )

																					_a			  =       []
																					_a			  =       []
																					for word, label in zip(example.words							,    example.labels      ):
																												_a			  =       tokenizer.tokenize(lowerCAmelCase_      )

																												# bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
																												if len(lowerCAmelCase_      ) > 0:
																																			tokens.extend(lowerCAmelCase_      )
																																			# Use the real label id for the first token of the word, and padding ids for the remaining tokens
																																			label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(lowerCAmelCase_      ) - 1)      )

            # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
																					_a			  =       tokenizer.num_special_tokens_to_add()
																					if len(lowerCAmelCase_      ) > max_seq_length - special_tokens_count:
																												_a			  =       tokens[: (max_seq_length - special_tokens_count)]
																												_a			  =       label_ids[: (max_seq_length - special_tokens_count)]

																					# The convention in BERT is:
																					# (a) For sequence pairs:
																					#  tokens:   [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
																					#  type_ids:   0   0  0    0    0     0       0   0   1  1  1  1   1   1
																					# (b) For single sequences:
																					#  tokens:   [CLS] the dog is hairy . [SEP]
																					#  type_ids:   0   0   0   0  0     0   0
																					#
																					# Where "type_ids" are used to indicate whether this is the first
																					# sequence or the second sequence. The embedding vectors for `type=0` and
																					# `type=1` were learned during pre-training and are added to the wordpiece
																					# embedding vector (and position vector). This is not *strictly* necessary
																					# since the [SEP] token unambiguously separates the sequences, but it makes
																					# it easier for the model to learn the concept of sequences.
																					#
																					# For classification tasks, the first vector (corresponding to [CLS]) is
																					# used as the "sentence vector". Note that this only makes sense because
																					# the entire model is fine-tuned.
																					tokens += [sep_token]
																					label_ids += [pad_token_label_id]
																					if sep_token_extra:
																												# roberta uses an extra separator b/w pairs of sentences
																												tokens += [sep_token]
																												label_ids += [pad_token_label_id]
																					_a			  =       [sequence_a_segment_id] * len(lowerCAmelCase_      )

																					if cls_token_at_end:
																												tokens += [cls_token]
																												label_ids += [pad_token_label_id]
																												segment_ids += [cls_token_segment_id]
																					else:
																												_a			  =       [cls_token] + tokens
																												_a			  =       [pad_token_label_id] + label_ids
																												_a			  =       [cls_token_segment_id] + segment_ids

																					_a			  =       tokenizer.convert_tokens_to_ids(lowerCAmelCase_      )

																					# The mask has 1 for real tokens and 0 for padding tokens. Only real
																					# tokens are attended to.
																					_a			  =       [1 if mask_padding_with_zero else 0] * len(lowerCAmelCase_      )

																					# Zero-pad up to the sequence length.
																					_a			  =       max_seq_length - len(lowerCAmelCase_      )
																					if pad_on_left:
																												_a			  =       ([pad_token] * padding_length) + input_ids
																												_a			  =       ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
																												_a			  =       ([pad_token_segment_id] * padding_length) + segment_ids
																												_a			  =       ([pad_token_label_id] * padding_length) + label_ids
																					else:
																												input_ids += [pad_token] * padding_length
																												input_mask += [0 if mask_padding_with_zero else 1] * padding_length
																												segment_ids += [pad_token_segment_id] * padding_length
																												label_ids += [pad_token_label_id] * padding_length

																					assert len(lowerCAmelCase_      ) == max_seq_length
																					assert len(lowerCAmelCase_      ) == max_seq_length
																					assert len(lowerCAmelCase_      ) == max_seq_length
																					assert len(lowerCAmelCase_      ) == max_seq_length

																					if ex_index < 5:
																												logger.info('''*** Example ***'''      )
																												logger.info('''guid: %s'''							,    example.guid      )
																												logger.info('''tokens: %s'''							,    ''' '''.join([str(lowerCAmelCase_      ) for x in tokens]      )      )
																												logger.info('''input_ids: %s'''							,    ''' '''.join([str(lowerCAmelCase_      ) for x in input_ids]      )      )
																												logger.info('''input_mask: %s'''							,    ''' '''.join([str(lowerCAmelCase_      ) for x in input_mask]      )      )
																												logger.info('''segment_ids: %s'''							,    ''' '''.join([str(lowerCAmelCase_      ) for x in segment_ids]      )      )
																												logger.info('''label_ids: %s'''							,    ''' '''.join([str(lowerCAmelCase_      ) for x in label_ids]      )      )

																					if "token_type_ids" not in tokenizer.model_input_names:
																												_a			  =       None

																					features.append(
																					    InputFeatures(
																					        input_ids=lowerCAmelCase_							,    attention_mask=lowerCAmelCase_							,    token_type_ids=lowerCAmelCase_							,    label_ids=lowerCAmelCase_      )      )
														return features


if is_torch_available():
				import torch
				from torch import nn
				from torch.utils.data import Dataset

				class     A					(	_a					):
											lowercase_           =       42
											lowercase_           =       nn.CrossEntropyLoss().ignore_index







											def __init__(						self :						int							,    lowerCAmelCase_ :						TokenClassificationTask							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						PreTrainedTokenizer							,    lowerCAmelCase_ :						List[str]							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						Optional[int] = None							,    lowerCAmelCase_ :						int=False							,    lowerCAmelCase_ :						Split = Split.train							,    )    ->							Union[str, Any]:


																		"""simple docstring"""


																		_a			  =       os.path.join(
																		    lowerCAmelCase_							,    '''cached_{}_{}_{}'''.format(mode.value							,    tokenizer.__class__.__name__							,    str(lowerCAmelCase_      )      )							,    )

																		# Make sure only the first process in distributed training processes the dataset,
																		# and the others will use the cache.
																		_a			  =       cached_features_file + '''.lock'''
																		with FileLock(lowerCAmelCase_      ):
																									if os.path.exists(lowerCAmelCase_      ) and not overwrite_cache:
																																logger.info(F'Loading features from cached file {cached_features_file}'      )
																																_a			  =       torch.load(lowerCAmelCase_      )
																									else:
																																logger.info(F'Creating features from dataset file at {data_dir}'      )
																																_a			  =       token_classification_task.read_examples_from_file(lowerCAmelCase_							,    lowerCAmelCase_      )
																																# TODO clean up all this to leverage built-in features of tokenizers
																																_a			  =       token_classification_task.convert_examples_to_features(
																																    lowerCAmelCase_							,    lowerCAmelCase_							,    lowerCAmelCase_							,    lowerCAmelCase_							,    cls_token_at_end=bool(model_type in ['''xlnet''']      )							,    cls_token=tokenizer.cls_token							,    cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0							,    sep_token=tokenizer.sep_token							,    sep_token_extra=lowerCAmelCase_							,    pad_on_left=bool(tokenizer.padding_side == '''left'''      )							,    pad_token=tokenizer.pad_token_id							,    pad_token_segment_id=tokenizer.pad_token_type_id							,    pad_token_label_id=self.pad_token_label_id							,    )
																																logger.info(F'Saving features into cached file {cached_features_file}'      )
																																torch.save(self.features							,    lowerCAmelCase_      )







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


																		"""simple docstring"""


																		return len(self.features      )







											def __getitem__(						self :						Tuple							,    lowerCAmelCase_ :						Any      )    ->							InputFeatures:


																		"""simple docstring"""


																		return self.features[i]


if is_tf_available():
				import tensorflow as tf

				class     A					:
											lowercase_           =       42
											lowercase_           =       -100







											def __init__(						self :						str							,    lowerCAmelCase_ :						TokenClassificationTask							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						PreTrainedTokenizer							,    lowerCAmelCase_ :						List[str]							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						Optional[int] = None							,    lowerCAmelCase_ :						int=False							,    lowerCAmelCase_ :						Split = Split.train							,    )    ->							int:


																		"""simple docstring"""


																		_a			  =       token_classification_task.read_examples_from_file(lowerCAmelCase_							,    lowerCAmelCase_      )
																		# TODO clean up all this to leverage built-in features of tokenizers
																		_a			  =       token_classification_task.convert_examples_to_features(
																		    lowerCAmelCase_							,    lowerCAmelCase_							,    lowerCAmelCase_							,    lowerCAmelCase_							,    cls_token_at_end=bool(model_type in ['''xlnet''']      )							,    cls_token=tokenizer.cls_token							,    cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0							,    sep_token=tokenizer.sep_token							,    sep_token_extra=lowerCAmelCase_							,    pad_on_left=bool(tokenizer.padding_side == '''left'''      )							,    pad_token=tokenizer.pad_token_id							,    pad_token_segment_id=tokenizer.pad_token_type_id							,    pad_token_label_id=self.pad_token_label_id							,    )

																		def gen():
																									for ex in self.features:
																																if ex.token_type_ids is None:
																																							yield (
																																							    {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
																																							    ex.label_ids,
																																							)
																																else:
																																							yield (
																																							    {
																																							        "input_ids": ex.input_ids,
																																							        "attention_mask": ex.attention_mask,
																																							        "token_type_ids": ex.token_type_ids,
																																							    },
																																							    ex.label_ids,
																																							)

																		if "token_type_ids" not in tokenizer.model_input_names:
																									_a			  =       tf.data.Dataset.from_generator(
																									    lowerCAmelCase_							,    ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa)							,    (
																									        {'''input_ids''': tf.TensorShape([None]      ), '''attention_mask''': tf.TensorShape([None]      )},
																									        tf.TensorShape([None]      ),
																									    )							,    )
																		else:
																									_a			  =       tf.data.Dataset.from_generator(
																									    lowerCAmelCase_							,    ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa)							,    (
																									        {
																									            '''input_ids''': tf.TensorShape([None]      ),
																									            '''attention_mask''': tf.TensorShape([None]      ),
																									            '''token_type_ids''': tf.TensorShape([None]      ),
																									        },
																									        tf.TensorShape([None]      ),
																									    )							,    )







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


																		"""simple docstring"""


																		_a			  =       self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features      )      )      )

																		return self.dataset







											def __len__(						self :						int      )    ->							Dict:


																		"""simple docstring"""


																		return len(self.features      )







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


																		"""simple docstring"""


																		return self.features[i]







'''simple docstring'''


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

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

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

from .utils import require_pil

class     A					(	_a					):







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Dict      )    ->							Dict:


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Any      )    ->							Tuple:


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Tuple      )    ->							Tuple:


														"""simple docstring"""


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







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


														"""simple docstring"""


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







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


														"""simple docstring"""


														import PIL.Image

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



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





							'''simple docstring'''


							_a			  =       pa.BufferReader(UpperCamelCase   ) if isinstance(UpperCamelCase				,		pa.Buffer   ) else pa.memory_map(UpperCamelCase   )
							_a			  =       pa.ipc.open_stream(UpperCamelCase   )
							_a			  =       f.read_all()
							assert len(pa_table.to_batches()   ) == expected_num_chunks
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
							del pa_table
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						str   ):





							'''simple docstring'''


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





							'''simple docstring'''


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





							'''simple docstring'''


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





							'''simple docstring'''


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





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ArrowWriter(
							    stream=UpperCamelCase				,		writer_batch_size=UpperCamelCase				,		hash_salt='''split_name'''				,		check_duplicates=UpperCamelCase				,		) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}				,		key=1   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}				,		key=2   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Dict				,		UpperCamelCase :						List[str]   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_batch({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )
														writer.write_batch({'''col_1''': [], '''col_2''': []}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						Any				,		UpperCamelCase :						Any   ):





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							_a			  =       pa.schema(UpperCamelCase   ) if fields else None
							with ArrowWriter(stream=UpperCamelCase				,		schema=UpperCamelCase				,		writer_batch_size=UpperCamelCase   ) as writer:
														writer.write_table(pa.Table.from_pydict({'''col_1''': ['''foo''', '''bar'''], '''col_2''': [1, 2]}   )   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							if not fields:
														_a			  =       {'''col_1''': pa.string(), '''col_2''': pa.intaa()}
							assert writer._schema == pa.schema(UpperCamelCase				,		metadata=writer._schema.metadata   )
							_check_output(output.getvalue()				,		expected_num_chunks=num_examples if writer_batch_size == 1 else 1   )
@pytest.mark.parametrize('''writer_batch_size'''				,		[None, 1, 10]   )
@pytest.mark.parametrize(
    '''fields'''				,		[None, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}, {'''col_1''': pa.string(), '''col_2''': pa.intaa()}]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


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





							'''simple docstring'''


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





							'''simple docstring'''


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





							'''simple docstring'''


							if isinstance(lst[0]				,		UpperCamelCase   ):
														change_first_primitive_element_in_list(lst[0]				,		UpperCamelCase   )
							else:
														_a			  =       value
@pytest.mark.parametrize('''optimized_int_type, expected_dtype'''				,		[(None, pa.intaa()), (Value('''int32'''   ), pa.intaa())]   )
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						int				,		UpperCamelCase :						Tuple				,		UpperCamelCase :						Optional[int]   ):





							'''simple docstring'''


							_a			  =       pa.array(TypedSequence(UpperCamelCase				,		optimized_int_type=UpperCamelCase   )   )
							assert get_base_dtype(arr.type   ) == expected_dtype
@pytest.mark.parametrize(
    '''col, expected_dtype'''				,		[
        ('''attention_mask''', pa.inta()),
        ('''special_tokens_mask''', pa.inta()),
        ('''token_type_ids''', pa.inta()),
        ('''input_ids''', pa.intaa()),
        ('''other''', pa.intaa()),
    ]				,		)
@pytest.mark.parametrize('''sequence'''				,		[[1, 2, 3], [[1, 2, 3]], [[[1, 2, 3]]]]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						str				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


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

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





							'''simple docstring'''


							_a			  =       str(tmp_path / '''dataset-train.arrow'''   )
							try:
														with ArrowWriter(path=UpperCamelCase   ) as writer:
																					if raise_exception:
																												raise pa.lib.ArrowInvalid()
																					else:
																												writer.stream.close()
							except pa.lib.ArrowInvalid:
														pass
							finally:
														assert writer.stream.closed
def 	snake_case_					(UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


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





							'''simple docstring'''


							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(stream=UpperCamelCase   ) as writer:
														writer.write({'''col_1''': '''foo''', '''col_2''': 1}   )
														writer.write({'''col_1''': '''bar''', '''col_2''': 2}   )
														_a  ,							_a			  =       writer.finalize()
							assert num_examples == 2
							assert num_bytes > 0
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							assert pa_table.to_pydict() == {"col_1": ["foo", "bar"], "col_2": [1, 2]}
@require_pil
@pytest.mark.parametrize('''embed_local_files'''				,		[False, True]   )
def 	snake_case_					(UpperCamelCase :						List[Any]				,		UpperCamelCase :						List[Any]   ):





							'''simple docstring'''


							import PIL.Image

							_a			  =       str(tmp_path / '''test_image_rgb.jpg'''   )
							PIL.Image.fromarray(np.zeros((5, 5)				,		dtype=np.uinta   )   ).save(UpperCamelCase				,		format='''png'''   )
							_a			  =       pa.BufferOutputStream()
							with ParquetWriter(
							    stream=UpperCamelCase				,		features=Features({'''image''': Image()}   )				,		embed_local_files=UpperCamelCase   ) as writer:
														writer.write({'''image''': image_path}   )
														writer.finalize()
							_a			  =       pa.BufferReader(output.getvalue()   )
							_a			  =       pq.read_table(UpperCamelCase   )
							_a			  =       pa_table.to_pydict()
							if embed_local_files:
														assert isinstance(out['''image'''][0]['''path''']				,		UpperCamelCase   )
														with open(UpperCamelCase				,		'''rb'''   ) as f:
																					assert out["image"][0]["bytes"] == f.read()
							else:
														assert out["image"][0]["path"] == image_path
														assert out["image"][0]["bytes"] is None

def 	snake_case_					():





							'''simple docstring'''


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

