'''simple docstring'''

import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse("""3.8"""):
  import importlib_metadata
else:
  import importlib.metadata as importlib_metadata
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase=False					):
 try:
  lowercase__    :   Dict						= os.environ[key]
 except KeyError:
  # KEY isn't set, default to `default`.
  lowercase__    :   List[Any]						= default
 else:
  # KEY is set, convert it to True or False.
  try:
   lowercase__    :   int						= strtobool(UpperCAmelCase					)
  except ValueError:
   # More values are supported, but let's keep the message simple.
   raise ValueError(F"""If set, {key} must be yes or no."""					)
 return _value


__a:			Dict	       =       parse_flag_from_env("""RUN_SLOW""", default=False)
__a:			Dict	       =       parse_flag_from_env("""RUN_REMOTE""", default=False)
__a:			Optional[Any]	       =       parse_flag_from_env("""RUN_LOCAL""", default=True)
__a:			Union[str, Any]	       =       parse_flag_from_env("""RUN_PACKAGED""", default=True)

# Compression
__a:			List[Any]	       =       pytest.mark.skipif(not config.LZ4_AVAILABLE, reason="""test requires lz4""")
__a:			Dict	       =       pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason="""test requires py7zr""")
__a:			Any	       =       pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason="""test requires zstandard""")

# Audio
__a:			Optional[int]	       =       pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec("""soundfile""") is None or version.parse(importlib_metadata.version("""soundfile""")) < version.parse("""0.12.0"""),
    reason="""test requires sndfile>=0.12.1: 'pip install \"soundfile>=0.12.1\"'; """,
)

# Beam
__a:			List[str]	       =       pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse("""0.3.2"""),
    reason="""test requires apache-beam and a compatible dill version""",
)

# Dill-cloudpickle compatibility
__a:			List[str]	       =       pytest.mark.skipif(
    config.DILL_VERSION <= version.parse("""0.3.2"""),
    reason="""test requires dill>0.3.2 for cloudpickle compatibility""",
)

# Windows
__a:			Any	       =       pytest.mark.skipif(
    sys.platform == """win32""",
    reason="""test should not be run on Windows""",
)
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import faiss  # noqa
 except ImportError:
  lowercase__    :   Any						= unittest.skip('''test requires faiss'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import regex  # noqa
 except ImportError:
  lowercase__    :   Optional[int]						= unittest.skip('''test requires regex'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import elasticsearch  # noqa
 except ImportError:
  lowercase__    :   List[str]						= unittest.skip('''test requires elasticsearch'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import sqlalchemy  # noqa
 except ImportError:
  lowercase__    :   Union[str, Any]						= unittest.skip('''test requires sqlalchemy'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.TORCH_AVAILABLE:
  lowercase__    :   Optional[Any]						= unittest.skip('''test requires PyTorch'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.TF_AVAILABLE:
  lowercase__    :   Any						= unittest.skip('''test requires TensorFlow'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.JAX_AVAILABLE:
  lowercase__    :   int						= unittest.skip('''test requires JAX'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not config.PIL_AVAILABLE:
  lowercase__    :   Any						= unittest.skip('''test requires Pillow'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import transformers  # noqa F401
 except ImportError:
  return unittest.skip('''test requires transformers'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import tiktoken  # noqa F401
 except ImportError:
  return unittest.skip('''test requires tiktoken'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import spacy  # noqa F401
 except ImportError:
  return unittest.skip('''test requires spacy'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):

 def _require_spacy_model(UpperCAmelCase					):
  try:
   import spacy  # noqa F401

   spacy.load(UpperCAmelCase					)
  except ImportError:
   return unittest.skip('''test requires spacy'''					)(UpperCAmelCase					)
  except OSError:
   return unittest.skip('''test requires spacy model \'{}\''''.format(UpperCAmelCase					)					)(UpperCAmelCase					)
  else:
   return test_case

 return _require_spacy_model
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import pyspark  # noqa F401
 except ImportError:
  return unittest.skip('''test requires pyspark'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 try:
  import joblibspark  # noqa F401
 except ImportError:
  return unittest.skip('''test requires joblibspark'''					)(UpperCAmelCase					)
 else:
  return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_slow_tests or _run_slow_tests == 0:
  lowercase__    :   int						= unittest.skip('''test is slow'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_local_tests or _run_local_tests == 0:
  lowercase__    :   Optional[int]						= unittest.skip('''test is local'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_packaged_tests or _run_packaged_tests == 0:
  lowercase__    :   Dict						= unittest.skip('''test is packaged'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       UpperCAmelCase					):
 if not _run_remote_tests or _run_remote_tests == 0:
  lowercase__    :   Dict						= unittest.skip('''test requires remote'''					)(UpperCAmelCase					)
 return test_case
def       __UpperCamelCase	(       *UpperCAmelCase					):
 def decorate(cls					):
  for name, fn in cls.__dict__.items():
   if callable(UpperCAmelCase					) and name.startswith('''test'''					):
    for decorator in decorators:
     lowercase__    :   List[Any]						= decorator(UpperCAmelCase					)
    setattr(cls		,					UpperCAmelCase		,					UpperCAmelCase					)
  return cls

 return decorate



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       pass



class       UpperCAmelCase  (						a__ ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   0
       SCREAMING_SNAKE_CASE 		=   1
       SCREAMING_SNAKE_CASE 		=   2


@contextmanager
def       __UpperCamelCase	(       UpperCAmelCase=OfflineSimulationMode.CONNECTION_FAILS		,					UpperCAmelCase=1E-16					):
 lowercase__    :   str						= requests.Session().request

 def timeout_request(UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					**UpperCAmelCase					):
  # Change the url to an invalid url so that the connection hangs
  lowercase__    :   int						= '''https://10.255.255.1'''
  if kwargs.get('''timeout'''					) is None:
   raise RequestWouldHangIndefinitelyError(
       F"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""					)
  lowercase__    :   List[str]						= timeout
  try:
   return online_request(UpperCAmelCase		,					UpperCAmelCase		,					**UpperCAmelCase					)
  except Exception as e:
   # The following changes in the error are just here to make the offline timeout error prettier
   lowercase__    :   Dict						= url
   lowercase__    :   Union[str, Any]						= e.args[0]
   lowercase__    :   Union[str, Any]						= (max_retry_error.args[0].replace('''10.255.255.1'''		,					F"""OfflineMock[{url}]"""					),)
   lowercase__    :   List[str]						= (max_retry_error,)
   raise

 def raise_connection_error(UpperCAmelCase		,					UpperCAmelCase		,					**UpperCAmelCase					):
  raise requests.ConnectionError('''Offline mode is enabled.'''		,					request=UpperCAmelCase					)

 if mode is OfflineSimulationMode.CONNECTION_FAILS:
  with patch('''requests.Session.send'''		,					UpperCAmelCase					):
   yield
 elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
  # inspired from https://stackoverflow.com/a/904609
  with patch('''requests.Session.request'''		,					UpperCAmelCase					):
   yield
 elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
  with patch('''datasets.config.HF_DATASETS_OFFLINE'''		,					UpperCAmelCase					):
   yield
 else:
  raise ValueError('''Please use a value from the OfflineSimulationMode enum.'''					)
@contextmanager
def       __UpperCamelCase	(       *UpperCAmelCase		,					**UpperCAmelCase					):
 lowercase__    :   Optional[int]						= str(Path().resolve()					)
 with tempfile.TemporaryDirectory(*UpperCAmelCase		,					**UpperCAmelCase					) as tmp_dir:
  try:
   os.chdir(UpperCAmelCase					)
   yield
  finally:
   os.chdir(UpperCAmelCase					)
@contextmanager
def       __UpperCamelCase	(       ):
 import gc

 gc.collect()
 lowercase__    :   Tuple						= pa.total_allocated_bytes()
 yield
 assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."
@contextmanager
def       __UpperCamelCase	(       ):
 import gc

 gc.collect()
 lowercase__    :   Optional[int]						= pa.total_allocated_bytes()
 yield
 assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase					):
 return deepcopy(UpperCAmelCase					).integers(0		,					100		,					10					).tolist() == deepcopy(UpperCAmelCase					).integers(0		,					100		,					10					).tolist()
def       __UpperCamelCase	(       UpperCAmelCase					):
 import decorator
 from requests.exceptions import HTTPError

 def _wrapper(UpperCAmelCase		,					*UpperCAmelCase		,					**UpperCAmelCase					):
  try:
   return func(*UpperCAmelCase		,					**UpperCAmelCase					)
  except HTTPError as err:
   if str(UpperCAmelCase					).startswith('''500'''					) or str(UpperCAmelCase					).startswith('''502'''					):
    pytest.xfail(str(UpperCAmelCase					)					)
   raise err

 return decorator.decorator(_wrapper		,					UpperCAmelCase					)



class       UpperCAmelCase  :





       '''simple docstring'''



       def __init__(						self     ,       __lowerCAmelCase     ,       __lowerCAmelCase     ,       __lowerCAmelCase			)  ->  Any:
        lowercase__    :   Any						= returncode
        lowercase__    :   Tuple						= stdout
        lowercase__    :   Any						= stderr


async def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase					):
 while True:
  lowercase__    :   Optional[Any]						= await stream.readline()
  if line:
   callback(UpperCAmelCase					)
  else:
   break
async def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase=None		,					UpperCAmelCase=None		,					UpperCAmelCase=None		,					UpperCAmelCase=False		,					UpperCAmelCase=False					):
 if echo:
  print('''\nRunning: '''		,					''' '''.join(UpperCAmelCase					)					)

 lowercase__    :   Tuple						= await asyncio.create_subprocess_exec(
     cmd[0]		,					*cmd[1:]		,					stdin=UpperCAmelCase		,					stdout=asyncio.subprocess.PIPE		,					stderr=asyncio.subprocess.PIPE		,					env=UpperCAmelCase		,					)

 # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
 # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
 #
 # If it starts hanging, will need to switch to the following code. The problem is that no data
 # will be seen until it's done and if it hangs for example there will be no debug info.
 # out, err = await p.communicate()
 # return _RunOutput(p.returncode, out, err)

 lowercase__    :   List[str]						= []
 lowercase__    :   Optional[int]						= []

 def tee(UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase=""					):
  lowercase__    :   Any						= line.decode('''utf-8'''					).rstrip()
  sink.append(UpperCAmelCase					)
  if not quiet:
   print(UpperCAmelCase		,					UpperCAmelCase		,					file=UpperCAmelCase					)

    # XXX: the timeout doesn't seem to make any difference here
 await asyncio.wait(
     [
         _read_stream(p.stdout		,					lambda UpperCAmelCase					: tee(UpperCAmelCase		,					UpperCAmelCase		,					sys.stdout		,					label='''stdout:'''					)					),
         _read_stream(p.stderr		,					lambda UpperCAmelCase					: tee(UpperCAmelCase		,					UpperCAmelCase		,					sys.stderr		,					label='''stderr:'''					)					),
     ]		,					timeout=UpperCAmelCase		,					)
 return _RunOutput(await p.wait()		,					UpperCAmelCase		,					UpperCAmelCase					)
def       __UpperCamelCase	(       UpperCAmelCase		,					UpperCAmelCase=None		,					UpperCAmelCase=None		,					UpperCAmelCase=180		,					UpperCAmelCase=False		,					UpperCAmelCase=True					):
 lowercase__    :   Dict						= asyncio.get_event_loop()
 lowercase__    :   Tuple						= loop.run_until_complete(
     _stream_subprocess(UpperCAmelCase		,					env=UpperCAmelCase		,					stdin=UpperCAmelCase		,					timeout=UpperCAmelCase		,					quiet=UpperCAmelCase		,					echo=UpperCAmelCase					)					)

 lowercase__    :   Tuple						= ''' '''.join(UpperCAmelCase					)
 if result.returncode > 0:
  lowercase__    :   Optional[int]						= '''\n'''.join(result.stderr					)
  raise RuntimeError(
      F"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
      F"""The combined stderr from workers follows:\n{stderr}"""					)

 # check that the subprocess actually did run and produced some output, should the test rely on
 # the remote side to do the testing
 if not result.stdout and not result.stderr:
  raise RuntimeError(F"""'{cmd_str}' produced no output."""					)

 return result
def       __UpperCamelCase	(       ):
 lowercase__    :   str						= os.environ.get('''PYTEST_XDIST_WORKER'''		,					'''gw0'''					)
 lowercase__    :   List[str]						= re.sub(r'''^gw'''		,					''''''		,					UpperCAmelCase		,					0		,					re.M					)
 return int(UpperCAmelCase					)





def       __UpperCamelCase	(       ):
 lowercase__    :   Any						= 2_9500
 lowercase__    :   List[Any]						= pytest_xdist_worker_id()
 return port + uniq_delta


'''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:			Tuple	       =       datasets.utils.logging.get_logger(__name__)



@dataclass
class       UpperCAmelCase  (						datasets.BuilderConfig ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   None
       SCREAMING_SNAKE_CASE 		=   "utf-8"
       SCREAMING_SNAKE_CASE 		=   None
       SCREAMING_SNAKE_CASE 		=   None
       SCREAMING_SNAKE_CASE 		=   True  # deprecated
       SCREAMING_SNAKE_CASE 		=   None  # deprecated
       SCREAMING_SNAKE_CASE 		=   1_0 << 2_0  # 10MB
       SCREAMING_SNAKE_CASE 		=   None



class       UpperCAmelCase  (						datasets.ArrowBasedBuilder ):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE 		=   JsonConfig

       def _lowerCAmelCase(						self			)  ->  Any:
        if self.config.block_size is not None:
         logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'''			)
         lowercase__    :   Tuple						= 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 _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[Any]:
        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__    :   List[str]						= dl_manager.download_and_extract(self.config.data_files			)
        if isinstance(__lowerCAmelCase     ,       (str, list, tuple)			):
         lowercase__    :   List[str]						= data_files
         if isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):
          lowercase__    :   Union[str, Any]						= [files]
         lowercase__    :   Dict						= [dl_manager.iter_files(__lowerCAmelCase			) 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(__lowerCAmelCase     ,       __lowerCAmelCase			):
          lowercase__    :   List[str]						= [files]
         lowercase__    :   Optional[Any]						= [dl_manager.iter_files(__lowerCAmelCase			) for file in files]
         splits.append(datasets.SplitGenerator(name=__lowerCAmelCase     ,       gen_kwargs={'''files''': files}			)			)
        return splits

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


       def _lowerCAmelCase(						self     ,       __lowerCAmelCase			)  ->  Optional[int]:
        for file_idx, file in enumerate(itertools.chain.from_iterable(__lowerCAmelCase			)			):
         # 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(__lowerCAmelCase     ,       encoding=self.config.encoding     ,       errors=self.config.encoding_errors			) as f:
           lowercase__    :   Dict						= json.load(__lowerCAmelCase			)

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

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

         # If the file has one json object per line
         else:
          with open(__lowerCAmelCase     ,       '''rb'''			) as f:
           lowercase__    :   Optional[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__    :   List[str]						= max(self.config.chunksize // 32     ,       16 << 10			)
           lowercase__    :   Union[str, Any]						= (
               self.config.encoding_errors if self.config.encoding_errors is not None else '''strict'''
           )
           while True:
            lowercase__    :   Tuple						= f.read(self.config.chunksize			)
            if not batch:
             break
            # Finish current line
            try:
             batch += f.readline()
            except (AttributeError, io.UnsupportedOperation):
             batch += readline(__lowerCAmelCase			)
            # PyArrow only accepts utf-8 encoded bytes
            if self.config.encoding != "utf-8":
             lowercase__    :   Dict						= batch.decode(self.config.encoding     ,       errors=__lowerCAmelCase			).encode('''utf-8'''			)
            try:
             while True:
              try:
               lowercase__    :   str						= paj.read_json(
                   io.BytesIO(__lowerCAmelCase			)     ,       read_options=paj.ReadOptions(block_size=__lowerCAmelCase			)			)
               break
              except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
               if (
                   isinstance(__lowerCAmelCase     ,       pa.ArrowInvalid			)
                   and "straddling" not in str(__lowerCAmelCase			)
                   or block_size > len(__lowerCAmelCase			)
               ):
                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(__lowerCAmelCase			)} 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(
                  __lowerCAmelCase     ,       encoding=self.config.encoding     ,       errors=self.config.encoding_errors			) as f:
               lowercase__    :   Optional[int]						= json.load(__lowerCAmelCase			)
             except json.JSONDecodeError:
              logger.error(F"""Failed to read file '{file}' with error {type(__lowerCAmelCase			)}: {e}"""			)
              raise e
             # If possible, parse the file as a list of json objects and exit the loop
             if isinstance(__lowerCAmelCase     ,       __lowerCAmelCase			):  # list is the only sequence type supported in JSON
              try:
               lowercase__    :   List[Any]						= set().union(*[row.keys() for row in dataset]			)
               lowercase__    :   str						= {col: [row.get(__lowerCAmelCase			) for row in dataset] for col in keys}
               lowercase__    :   Optional[int]						= pa.Table.from_pydict(__lowerCAmelCase			)
              except (pa.ArrowInvalid, AttributeError) as e:
               logger.error(F"""Failed to read file '{file}' with error {type(__lowerCAmelCase			)}: {e}"""			)
               raise ValueError(F"""Not able to read records in the JSON file at {file}."""			) from None
              yield file_idx, self._cast_table(__lowerCAmelCase			)
              break
             else:
              logger.error(F"""Failed to read file '{file}' with error {type(__lowerCAmelCase			)}: {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(__lowerCAmelCase			)
            batch_idx += 1

