
"""simple docstring"""




import random
import unittest

from torch.utils.data import BatchSampler, DataLoader, IterableDataset

from accelerate import Accelerator
from accelerate.data_loader import (
    BatchSamplerShard,
    DataLoaderDispatcher,
    DataLoaderShard,
    IterableDatasetShard,
    SkipBatchSampler,
    SkipDataLoader,
    skip_first_batches,
)


class 			__magic_name__       (       a__ ):
							def __init__(     self ,				A_=0.01 ,				A_=1000       )     ->	Tuple:





									"""simple docstring"""




									_lowercase:			Tuple       =     p_stop
									_lowercase:			str       =     max_length



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





									"""simple docstring"""




									_lowercase:			str       =     0
									_lowercase:			List[Any]       =     False
									while not stop and count < self.max_length:
											yield count
											count += 1
											_lowercase:			Any       =     random.random() < self.p_stop


class 			__magic_name__       (       unittest.TestCase ):
							def 							lowercase_							(     self ,				A_ ,				A_ ,				A_=False ,				A_=True       )     ->	str:





									"""simple docstring"""




									_lowercase:			Tuple       =     [
									    BatchSamplerShard(_A ,				2 ,				_A ,				split_batches=_A ,				even_batches=_A       )
									    for i in range(2       )
									]
									_lowercase:			Optional[int]       =     [list(_A       ) for batch_sampler_shard in batch_sampler_shards]
									if not split_batches:
											self.assertListEqual([len(_A       ) for shard in batch_sampler_shards] ,				[len(_A       ) for e in expected]       )
									self.assertListEqual(_A ,				_A       )
							def 							lowercase_							(     self       )     ->	Union[str, Any]:





									"""simple docstring"""




									_lowercase:			Union[str, Any]       =     BatchSampler(range(24       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			int       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									_lowercase:			int       =     BatchSampler(range(24       ) ,				batch_size=3 ,				drop_last=_A       )
									# Expected shouldn't change
									self.check_batch_sampler_shards(_A ,				_A       )

									# Check the shards when the dataset is a round multiple of batch size but not total batch size.
									_lowercase:			Union[str, Any]       =     BatchSampler(range(21       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			int       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									_lowercase:			Dict       =     BatchSampler(range(21       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			List[str]       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									# Check the shards when the dataset is not a round multiple of batch size but has a multiple of
									# num_processes batch.
									_lowercase:			Dict       =     BatchSampler(range(22       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			List[Any]       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									_lowercase:			int       =     BatchSampler(range(22       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Optional[int]       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									# Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of
									# num_processes batch.
									_lowercase:			List[str]       =     BatchSampler(range(20       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Optional[int]       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									_lowercase:			str       =     BatchSampler(range(20       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Dict       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A       )

									# Check the shards when the dataset is very small.
									_lowercase:			int       =     BatchSampler(range(2       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			int       =     [[[0, 1, 0]], [[1, 0, 1]]]
									self.check_batch_sampler_shards(_A ,				_A       )

									_lowercase:			Union[str, Any]       =     BatchSampler(range(2       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			List[str]       =     [[], []]
									self.check_batch_sampler_shards(_A ,				_A       )
							def 							lowercase_							(     self       )     ->	Optional[Any]:





									"""simple docstring"""




									_lowercase:			Optional[int]       =     BatchSampler(range(24       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Optional[int]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									_lowercase:			List[Any]       =     BatchSampler(range(24       ) ,				batch_size=4 ,				drop_last=_A       )
									# Expected shouldn't change
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									# Check the shards when the dataset is not a round multiple of batch size.
									_lowercase:			Tuple       =     BatchSampler(range(22       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Optional[Any]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									_lowercase:			Optional[Any]       =     BatchSampler(range(22       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Optional[int]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									# Check the shards when the dataset is not a round multiple of batch size or num_processes.
									_lowercase:			Tuple       =     BatchSampler(range(21       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Union[str, Any]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									_lowercase:			int       =     BatchSampler(range(21       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			int       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									# Check the shards when the dataset is very small.
									_lowercase:			Tuple       =     BatchSampler(range(2       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			List[str]       =     [[[0, 1]], [[0, 1]]]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )

									_lowercase:			List[str]       =     BatchSampler(range(2       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Tuple       =     [[], []]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A       )
							def 							lowercase_							(     self       )     ->	Optional[Any]:





									"""simple docstring"""




									_lowercase:			Union[str, Any]       =     BatchSampler(range(24       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Any       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									_lowercase:			Dict       =     BatchSampler(range(24       ) ,				batch_size=3 ,				drop_last=_A       )
									# Expected shouldn't change
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									# Check the shards when the dataset is a round multiple of batch size but not total batch size.
									_lowercase:			Tuple       =     BatchSampler(range(21       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			int       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									_lowercase:			Optional[int]       =     BatchSampler(range(21       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			str       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									# Check the shards when the dataset is not a round multiple of batch size but has a multiple of
									# num_processes batch.
									_lowercase:			str       =     BatchSampler(range(22       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Tuple       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									_lowercase:			Union[str, Any]       =     BatchSampler(range(22       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Dict       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									# Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of
									# num_processes batch.
									_lowercase:			Tuple       =     BatchSampler(range(20       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			str       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									_lowercase:			List[Any]       =     BatchSampler(range(20       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Dict       =     [
									    [[0, 1, 2], [6, 7, 8], [12, 13, 14]],
									    [[3, 4, 5], [9, 10, 11], [15, 16, 17]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									# Check the shards when the dataset is very small.
									_lowercase:			int       =     BatchSampler(range(2       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			Dict       =     [[[0, 1]], []]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )

									_lowercase:			str       =     BatchSampler(range(2       ) ,				batch_size=3 ,				drop_last=_A       )
									_lowercase:			str       =     [[], []]
									self.check_batch_sampler_shards(_A ,				_A ,				even_batches=_A       )
							def 							lowercase_							(     self       )     ->	Dict:





									"""simple docstring"""




									_lowercase:			Optional[int]       =     BatchSampler(range(24       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Optional[int]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									_lowercase:			str       =     BatchSampler(range(24       ) ,				batch_size=4 ,				drop_last=_A       )
									# Expected shouldn't change
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									# Check the shards when the dataset is not a round multiple of batch size.
									_lowercase:			List[str]       =     BatchSampler(range(22       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Optional[Any]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									_lowercase:			Union[str, Any]       =     BatchSampler(range(22       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			List[Any]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									# Check the shards when the dataset is not a round multiple of batch size or num_processes.
									_lowercase:			int       =     BatchSampler(range(21       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Any       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									_lowercase:			Any       =     BatchSampler(range(21       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Optional[int]       =     [
									    [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]],
									    [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]],
									]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									# Check the shards when the dataset is very small.
									_lowercase:			Dict       =     BatchSampler(range(2       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			int       =     [[[0, 1]], []]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )

									_lowercase:			Dict       =     BatchSampler(range(2       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			Tuple       =     [[], []]
									self.check_batch_sampler_shards(_A ,				_A ,				split_batches=_A ,				even_batches=_A       )
							def 							lowercase_							(     self       )     ->	str:





									"""simple docstring"""




									_lowercase:			Tuple       =     [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]]
									_lowercase:			Tuple       =     [BatchSamplerShard(_A ,				2 ,				_A ,				even_batches=_A       ) for i in range(2       )]

									self.assertEqual(len(batch_sampler_shards[0]       ) ,				3       )
									self.assertEqual(len(batch_sampler_shards[1]       ) ,				2       )

									self.assertListEqual(list(batch_sampler_shards[0]       ) ,				[[0, 1, 2], [5, 6, 7, 8], [12, 13]]       )
									self.assertListEqual(list(batch_sampler_shards[1]       ) ,				[[3, 4], [9, 10, 11]]       )
							def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_=False ,				A_=2 ,				A_=False       )     ->	Union[str, Any]:





									"""simple docstring"""




									random.seed(_A       )
									_lowercase:			Tuple       =     list(_A       )

									_lowercase:			List[str]       =     [
									    IterableDatasetShard(
									        _A ,				batch_size=_A ,				drop_last=_A ,				num_processes=_A ,				process_index=_A ,				split_batches=_A ,				)
									    for i in range(_A       )
									]
									_lowercase:			Any       =     []
									for iterable_dataset_shard in iterable_dataset_shards:
											# Since our random iterable dataset will be... random... we need to use a seed to get reproducible results.
											random.seed(_A       )
											iterable_dataset_lists.append(list(_A       )       )

									_lowercase:			Union[str, Any]       =     batch_size // num_processes if split_batches else batch_size
									# All iterable dataset shard should have the same length, a round multiple of shard_batch_size
									_lowercase:			Dict       =     iterable_dataset_lists[0]
									for l in iterable_dataset_lists[1:]:
											self.assertEqual(len(_A       ) ,				len(_A       )       )
											self.assertTrue(len(_A       ) % shard_batch_size == 0       )

									_lowercase:			Union[str, Any]       =     []
									for idx in range(0 ,				len(_A       ) ,				_A       ):
											for l in iterable_dataset_lists:
													observed += l[idx : idx + shard_batch_size]

									if not drop_last:
											while len(_A       ) < len(_A       ):
													reference += reference
									self.assertListEqual(_A ,				reference[: len(_A       )]       )
							def 							lowercase_							(     self       )     ->	Tuple:





									"""simple docstring"""




									_lowercase:			Dict       =     42
									_lowercase:			Union[str, Any]       =     RandomIterableDataset()

									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )

									# Edge case with a very small dataset
									_lowercase:			Optional[int]       =     RandomIterableDataset(max_length=2       )

									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
									self.check_iterable_dataset_shards(_A ,				_A ,				batch_size=4 ,				drop_last=_A ,				split_batches=_A       )
							def 							lowercase_							(     self       )     ->	Any:





									"""simple docstring"""




									_lowercase:			Dict       =     BatchSampler(range(16       ) ,				batch_size=4 ,				drop_last=_A       )
									_lowercase:			int       =     SkipBatchSampler(_A ,				2       )
									self.assertListEqual(list(_A       ) ,				[[8, 9, 10, 11], [12, 13, 14, 15]]       )
							def 							lowercase_							(     self       )     ->	str:





									"""simple docstring"""




									_lowercase:			List[str]       =     SkipDataLoader(list(range(16       )       ) ,				batch_size=4 ,				skip_batches=2       )
									self.assertListEqual([t.tolist() for t in dataloader] ,				[[8, 9, 10, 11], [12, 13, 14, 15]]       )
							def 							lowercase_							(     self       )     ->	Optional[int]:





									"""simple docstring"""




									_lowercase:			Optional[int]       =     DataLoader(list(range(16       )       ) ,				batch_size=4       )
									_lowercase:			int       =     skip_first_batches(_A ,				num_batches=2       )
									self.assertListEqual([t.tolist() for t in new_dataloader] ,				[[8, 9, 10, 11], [12, 13, 14, 15]]       )
							def 							lowercase_							(     self       )     ->	Union[str, Any]:





									"""simple docstring"""




									_lowercase:			List[str]       =     DataLoaderShard(list(range(16       )       ) ,				batch_size=4       )
									for idx, _ in enumerate(_A       ):
											self.assertEqual(dataloader.end_of_dataloader ,				idx == 3       )

									# Test it also works on the second iteration
									for idx, _ in enumerate(_A       ):
											self.assertEqual(dataloader.end_of_dataloader ,				idx == 3       )



							def 							lowercase_							(     self       )     ->	int:





									"""simple docstring"""




									Accelerator()
									_lowercase:			Tuple       =     DataLoaderDispatcher(range(16       ) ,				batch_size=4       )
									for idx, _ in enumerate(_A       ):
											self.assertEqual(dataloader.end_of_dataloader ,				idx == 3       )

									# Test it also works on the second iteration
									for idx, _ in enumerate(_A       ):
											self.assertEqual(dataloader.end_of_dataloader ,				idx == 3       )


"""simple docstring"""




import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


A__   :					List[Any]							=   datasets.utils.logging.get_logger(__name__)


@dataclass
class 			__magic_name__       (       datasets.BuilderConfig ):
       UpperCamelCase_   =		None
       UpperCamelCase_   =		"utf-8"
       UpperCamelCase_   =		None
       UpperCamelCase_   =		None
       UpperCamelCase_   =		True  # deprecated
       UpperCamelCase_   =		None  # deprecated
       UpperCamelCase_   =		10 << 20  # 10MB
       UpperCamelCase_   =		None


class 			__magic_name__       (       datasets.ArrowBasedBuilder ):
       UpperCamelCase_   =		JsonConfig
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         if self.config.block_size is not None:
           logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''       )
           _lowercase:			List[str]       =     self.config.block_size
         if self.config.use_threads is not True:
           logger.warning(
               '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'''       )
         if self.config.newlines_in_values is not None:
           raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported'''       )
         return datasets.DatasetInfo(features=self.config.features       )
       def 							lowercase_							(     self ,				A_       )     ->	Any:





         """simple docstring"""




         if not self.config.data_files:
           raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''       )
         _lowercase:			int       =     dl_manager.download_and_extract(self.config.data_files       )
         if isinstance(A_ ,				(str, list, tuple)       ):
           _lowercase:			Tuple       =     data_files
           if isinstance(A_ ,				A_       ):
             _lowercase:			Optional[Any]       =     [files]
           _lowercase:			Dict       =     [dl_manager.iter_files(A_       ) for file in files]
           return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,				gen_kwargs={'''files''': files}       )]
         _lowercase:			str       =     []
         for split_name, files in data_files.items():
           if isinstance(A_ ,				A_       ):
             _lowercase:			Optional[Any]       =     [files]
           _lowercase:			str       =     [dl_manager.iter_files(A_       ) for file in files]
           splits.append(datasets.SplitGenerator(name=A_ ,				gen_kwargs={'''files''': files}       )       )
         return splits
       def 							lowercase_							(     self ,				A_       )     ->	pa.Table:





         """simple docstring"""




         if self.config.features is not None:
           # adding missing columns
           for column_name in set(self.config.features       ) - set(pa_table.column_names       ):
             _lowercase:			Any       =     self.config.features.arrow_schema.field(A_       ).type
             _lowercase:			Optional[Any]       =     pa_table.append_column(A_ ,				pa.array([None] * len(A_       ) ,				type=A_       )       )
           # more expensive cast to support nested structures with keys in a different order
           # allows str <-> int/float or str to Audio for example
           _lowercase:			Optional[int]       =     table_cast(A_ ,				self.config.features.arrow_schema       )
         return pa_table



       def 							lowercase_							(     self ,				A_       )     ->	str:





         """simple docstring"""




         for file_idx, file in enumerate(itertools.chain.from_iterable(A_       )       ):
           # If the file is one json object and if we need to look at the list of items in one specific field
           if self.config.field is not None:
             with open(A_ ,				encoding=self.config.encoding ,				errors=self.config.encoding_errors       ) as f:
               _lowercase:			Optional[int]       =     json.load(A_       )

             # We keep only the field we are interested in
             _lowercase:			str       =     dataset[self.config.field]

             # We accept two format: a list of dicts or a dict of lists
             if isinstance(A_ ,				(list, tuple)       ):
               _lowercase:			Dict       =     set().union(*[row.keys() for row in dataset]       )
               _lowercase:			List[str]       =     {col: [row.get(A_       ) for row in dataset] for col in keys}
             else:
               _lowercase:			Dict       =     dataset
             _lowercase:			Union[str, Any]       =     pa.Table.from_pydict(A_       )
             yield file_idx, self._cast_table(A_       )

           # If the file has one json object per line
           else:
             with open(A_ ,				'''rb'''       ) as f:
               _lowercase:			int       =     0
               # Use block_size equal to the chunk size divided by 32 to leverage multithreading
               # Set a default minimum value of 16kB if the chunk size is really small
               _lowercase:			Optional[int]       =     max(self.config.chunksize // 32 ,				16 << 10       )
               _lowercase:			List[Any]       =     (
                   self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
               )
               while True:
                 _lowercase:			Union[str, Any]       =     f.read(self.config.chunksize       )
                 if not batch:
                   break
                 # Finish current line
                 try:
                   batch += f.readline()
                 except (AttributeError, io.UnsupportedOperation):
                   batch += readline(A_       )
                 # PyArrow only accepts utf-8 encoded bytes
                 if self.config.encoding != "utf-8":
                   _lowercase:			Any       =     batch.decode(self.config.encoding ,				errors=A_       ).encode('''utf-8'''       )
                 try:
                   while True:
                     try:
                       _lowercase:			Optional[int]       =     paj.read_json(
                           io.BytesIO(A_       ) ,				read_options=paj.ReadOptions(block_size=A_       )       )
                       break
                     except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                       if (
                           isinstance(A_ ,				pa.ArrowInvalid       )
                           and "straddling" not in str(A_       )
                           or block_size > len(A_       )
                       ):
                         raise
                       else:
                         # Increase the block size in case it was too small.
                         # The block size will be reset for the next file.
                         logger.debug(
                             f'''Batch of {len(A_       )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.'''       )
                         block_size *= 2
                 except pa.ArrowInvalid as e:
                   try:
                     with open(
                         A_ ,				encoding=self.config.encoding ,				errors=self.config.encoding_errors       ) as f:
                       _lowercase:			Optional[Any]       =     json.load(A_       )
                   except json.JSONDecodeError:
                     logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                     raise e
                   # If possible, parse the file as a list of json objects and exit the loop
                   if isinstance(A_ ,				A_       ):  # list is the only sequence type supported in JSON
                     try:
                       _lowercase:			Optional[int]       =     set().union(*[row.keys() for row in dataset]       )
                       _lowercase:			Tuple       =     {col: [row.get(A_       ) for row in dataset] for col in keys}
                       _lowercase:			str       =     pa.Table.from_pydict(A_       )
                     except (pa.ArrowInvalid, AttributeError) as e:
                       logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                       raise ValueError(f'''Not able to read records in the JSON file at {file}.'''       ) from None
                     yield file_idx, self._cast_table(A_       )
                     break
                   else:
                     logger.error(f'''Failed to read file \'{file}\' with error {type(A_       )}: {e}'''       )
                     raise ValueError(
                         f'''Not able to read records in the JSON file at {file}. '''
                         f'''You should probably indicate the field of the JSON file containing your records. '''
                         f'''This JSON file contain the following fields: {str(list(dataset.keys()       )       )}. '''
                         f'''Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. '''       ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                 yield (file_idx, batch_idx), self._cast_table(A_       )
                 batch_idx += 1
