
'''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


__lowercase							:   Union[str, Any]					=     datasets.utils.logging.get_logger(__name__)

@dataclass
class 	__lowercase				(  datasets.BuilderConfig    ):
			lowerCamelCase			:		Optional[datasets.Features]	      =			None
			lowerCamelCase			:		str	      =			"utf-8"
			lowerCamelCase			:		Optional[str]	      =			None
			lowerCamelCase			:		Optional[str]	      =			None
			lowerCamelCase			:		bool	      =			True  # deprecated
			lowerCamelCase			:		Optional[int]	      =			None  # deprecated
			lowerCamelCase			:		int	      =			10 << 20  # 10MB
			lowerCamelCase			:		Optional[bool]	      =			None

class 	__lowercase				(  datasets.ArrowBasedBuilder    ):
			lowerCamelCase			:		Any	      =			JsonConfig

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

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






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

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

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

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




'''simple docstring'''


def lowercase_	(   _lowercase			,       _lowercase				)     ->							Dict:
					'''simple docstring'''

					lowerCamelCase_					:      List[Any]     =		0
					while b > 0:
										if b & 1:
															res += a

										a += a
										b >>= 1

					return res




def lowercase_	(   _lowercase			,       _lowercase			,       _lowercase				)     ->							Optional[Any]:
					'''simple docstring'''

					lowerCamelCase_					:      str     =		0
					while b > 0:
										if b & 1:
															lowerCamelCase_					:      Optional[int]     =		((res % c) + (a % c)) % c

										a += a
										b >>= 1

					return res


