
"""simple docstring"""



import json
import os
from typing import Dict, List, Optional, Tuple

import regex as re

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


a					:	Any							=		logging.get_logger(__name__)


a					:	Any							=		{
    '''vocab_file''': '''vocab.json''',
    '''merges_file''': '''merges.txt''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

a					:	Any							=		{
    '''vocab_file''': {
        '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json'''
    },
    '''merges_file''': {
        '''facebook/blenderbot_small-90M''': '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt'''
    },
    '''tokenizer_config_file''': {
        '''facebook/blenderbot_small-90M''': (
            '''https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json'''
        )
    },
}

a					:	List[Any]							=		{'''facebook/blenderbot_small-90M''': 5_1_2}


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





    """simple docstring"""

    _UpperCAmelCase          =   set()
    _UpperCAmelCase          =   word[0]
    for char in word[1:]:
        pairs.add((prev_char, char)      )
        _UpperCAmelCase          =   char

    _UpperCAmelCase          =   set(lowerCamelCase__      )
    return pairs







class 		a_						( _UpperCamelCase	):
    a      :				Optional[Any]     =				VOCAB_FILES_NAMES
    a      :				Any     =				PRETRAINED_VOCAB_FILES_MAP
    a      :				List[Any]     =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    a      :				Any     =				['input_ids', 'attention_mask']







    def __init__(			self			:       int     ,					__UpperCamelCase			:       Tuple     ,					__UpperCamelCase			:       List[str]     ,					__UpperCamelCase			:       List[str]="__start__"     ,					__UpperCamelCase			:       Any="__end__"     ,					__UpperCamelCase			:       Dict="__unk__"     ,					__UpperCamelCase			:       Union[str, Any]="__null__"     ,					**__UpperCamelCase			:       str     ,					)		->str:






        '''simple docstring'''






        super().__init__(unk_token=__UpperCamelCase     ,					bos_token=__UpperCamelCase     ,					eos_token=__UpperCamelCase     ,					pad_token=__UpperCamelCase     ,					**__UpperCamelCase     )

        with open(__UpperCamelCase     ,					encoding="""utf-8"""     ) as vocab_handle:
            _UpperCAmelCase          =   json.load(__UpperCamelCase     )
        _UpperCAmelCase          =   {v: k for k, v in self.encoder.items()}
        with open(__UpperCamelCase     ,					encoding="""utf-8"""     ) as merges_handle:
            _UpperCAmelCase          =   merges_handle.read().split("""\n"""     )[1:-1]
        _UpperCAmelCase          =   [tuple(merge.split()     ) for merge in merges]
        _UpperCAmelCase          =   dict(zip(__UpperCamelCase     ,					range(len(__UpperCamelCase     )     )     )     )
        _UpperCAmelCase          =   {}







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






        '''simple docstring'''






        return len(self.encoder     )







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






        '''simple docstring'''






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







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






        '''simple docstring'''






        if token in self.cache:
            return self.cache[token]
        _UpperCAmelCase          =   re.sub("""([.,!?()])"""     ,					r""" \1"""     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   re.sub("""(')"""     ,					r""" \1 """     ,					__UpperCamelCase     )
        _UpperCAmelCase          =   re.sub(r"""\s{2,}"""     ,					""" """     ,					__UpperCamelCase     )
        if "\n" in token:
            _UpperCAmelCase          =   token.replace("""\n"""     ,					""" __newln__"""     )

        _UpperCAmelCase          =   token.split(""" """     )
        _UpperCAmelCase          =   []
        for token in tokens:
            if not len(__UpperCamelCase     ):
                continue

            _UpperCAmelCase          =   token.lower()
            _UpperCAmelCase          =   tuple(__UpperCamelCase     )
            _UpperCAmelCase          =   tuple(list(word[:-1]     ) + [word[-1] + """</w>"""]     )
            _UpperCAmelCase          =   get_pairs(__UpperCamelCase     )

            if not pairs:
                words.append(__UpperCamelCase     )
                continue

            while True:
                _UpperCAmelCase          =   min(__UpperCamelCase     ,					key=lambda __UpperCamelCase     : self.bpe_ranks.get(__UpperCamelCase     ,					float("""inf"""     )     )     )
                if bigram not in self.bpe_ranks:
                    break
                _UpperCAmelCase          =   bigram
                _UpperCAmelCase          =   []
                _UpperCAmelCase          =   0

                while i < len(__UpperCamelCase     ):
                    try:
                        _UpperCAmelCase          =   word.index(__UpperCamelCase     ,					__UpperCamelCase     )
                        new_word.extend(word[i:j]     )
                        _UpperCAmelCase          =   j
                    except ValueError:
                        new_word.extend(word[i:]     )
                        break

                    if word[i] == first and i < len(__UpperCamelCase     ) - 1 and word[i + 1] == second:
                        new_word.append(first + second     )
                        i += 2
                    else:
                        new_word.append(word[i]     )
                        i += 1
                _UpperCAmelCase          =   tuple(__UpperCamelCase     )
                _UpperCAmelCase          =   new_word
                if len(__UpperCamelCase     ) == 1:
                    break
                else:
                    _UpperCAmelCase          =   get_pairs(__UpperCamelCase     )
            _UpperCAmelCase          =   "@@ ".join(__UpperCamelCase     )
            _UpperCAmelCase          =   word[:-4]

            _UpperCAmelCase          =   word
            words.append(__UpperCamelCase     )
        return " ".join(__UpperCamelCase     )







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






        '''simple docstring'''






        _UpperCAmelCase          =   []

        _UpperCAmelCase          =   re.findall(r"""\S+\n?"""     ,					__UpperCamelCase     )

        for token in words:
            split_tokens.extend(list(self.bpe(__UpperCamelCase     ).split(""" """     )     )     )
        return split_tokens







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






        '''simple docstring'''






        _UpperCAmelCase          =   token.lower()
        return self.encoder.get(__UpperCamelCase     ,					self.encoder.get(self.unk_token     )     )







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






        '''simple docstring'''






        return self.decoder.get(__UpperCamelCase     ,					self.unk_token     )







    def      _snake_case					(			self			:       int     ,					__UpperCamelCase			:       List[str]     )		->Optional[int]:






        '''simple docstring'''






        _UpperCAmelCase          =   " ".join(__UpperCamelCase     ).replace("""@@ """     ,					""""""     ).strip()
        return out_string







    def      _snake_case					(			self			:       Any     ,					__UpperCamelCase			:       str     ,					__UpperCamelCase			:       Optional[str] = None     )		->int:






        '''simple docstring'''






        if not os.path.isdir(__UpperCamelCase     ):
            logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""     )
            return
        _UpperCAmelCase          =   os.path.join(
            __UpperCamelCase     ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]     )
        _UpperCAmelCase          =   os.path.join(
            __UpperCamelCase     ,					(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]     )

        with open(__UpperCamelCase     ,					"""w"""     ,					encoding="""utf-8"""     ) as f:
            f.write(json.dumps(self.encoder     ,					indent=2     ,					sort_keys=__UpperCamelCase     ,					ensure_ascii=__UpperCamelCase     ) + """\n"""     )

        _UpperCAmelCase          =   0
        with open(__UpperCamelCase     ,					"""w"""     ,					encoding="""utf-8"""     ) as writer:
            writer.write("""#version: 0.2\n"""     )
            for bpe_tokens, token_index in sorted(self.bpe_ranks.items()     ,					key=lambda __UpperCamelCase     : kv[1]     ):
                if index != token_index:
                    logger.warning(
                        f"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
                        """ Please check that the tokenizer is not corrupted!"""     )
                    _UpperCAmelCase          =   token_index
                writer.write(""" """.join(__UpperCamelCase     ) + """\n"""     )
                index += 1

        return vocab_file, merge_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 		a_						( _UpperCAmelCase	):







    def      _snake_case					(			self			:       str     )		->str:






        '''simple docstring'''






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







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






        '''simple docstring'''






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







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






        '''simple docstring'''






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







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






        '''simple docstring'''






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







    def      _snake_case					(			self			:       str     )		->Dict:






        '''simple docstring'''






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







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






        '''simple docstring'''






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







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






        '''simple docstring'''






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







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






        '''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			:       List[Any]     )		->Optional[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[str]     )		->int:






        '''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			:       Optional[int]     )		->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			:       str     )		->Optional[Any]:






        '''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      )    ->  Any:





    """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      )    ->  Optional[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	(						)    ->  Union[str, Any]:





    """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      )    ->  Optional[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      )    ->  Tuple:





    """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      )    ->  List[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      )    ->  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_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      )    ->  List[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_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	(						)    ->  str:





    """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      )    ->  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      )    ->  Any:





    """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      )    ->  Dict:





    """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      )    ->  str:





    """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      )    ->  Dict:





    """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      )    ->  Dict:





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





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





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