




import functools
import gc
import inspect

import torch

from .imports import is_npu_available, is_xpu_available





def __UpperCamelCase			(       *_A  ):
						if not isinstance(_A ,  _A  ):
												lowerCAmelCase_      			=  list(_A  )
						for i in range(len(_A  )  ):
												lowerCAmelCase_      			=  None
						gc.collect()
						if is_xpu_available():
												torch.xpu.empty_cache()
						elif is_npu_available():
												torch.npu.empty_cache()
						else:
												torch.cuda.empty_cache()
						return objects





def __UpperCamelCase			(       _A  ):
						lowerCAmelCase_      			=  [
						    '''CUDA out of memory.''',  # CUDA OOM
						    '''cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.''',  # CUDNN SNAFU
						    '''DefaultCPUAllocator: can\'t allocate memory''',  # CPU OOM
						]
						if isinstance(_A ,  _A  ) and len(exception.args  ) == 1:
												return any(err in exception.args[0] for err in _statements  )
						return False






def __UpperCamelCase			(       _A = None ,  _A = 128  ):
						if function is None:
												return functools.partial(_A ,  starting_batch_size=_A  )

						lowerCAmelCase_      			=  starting_batch_size

						def decorator(*_A ,  **_A  ):
												nonlocal batch_size
												gc.collect()
												if is_xpu_available():
																		torch.xpu.empty_cache()
												elif is_npu_available():
																		torch.npu.empty_cache()
												else:
																		torch.cuda.empty_cache()
												lowerCAmelCase_      			=  list(inspect.signature(_A  ).parameters.keys()  )
												# Guard against user error
												if len(_A  ) < (len(_A  ) + 1):
																		lowerCAmelCase_      			=  ''', '''.join([f"{arg}={value}" for arg, value in zip(params[1:] ,  args[1:]  )]  )
																		raise TypeError(
																		    f"Batch size was passed into `{function.__name__}` as the first argument when called."
																		    f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`"  )
												while True:
																		if batch_size == 0:
																								raise RuntimeError('''No executable batch size found, reached zero.'''  )
																		try:
																								return function(_A ,  *_A ,  **_A  )
																		except Exception as e:
																								if should_reduce_batch_size(_A  ):
																														gc.collect()
																														if is_xpu_available():
																																				torch.xpu.empty_cache()
																														elif is_npu_available():
																																				torch.npu.empty_cache()
																														else:
																																				torch.cuda.empty_cache()
																														batch_size //= 2
																								else:
																														raise

						return decorator










import io
import json

import fsspec
import pytest

from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.json import JsonDatasetReader, JsonDatasetWriter

from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases





def __UpperCamelCase			(       _A ,  _A  ):
						assert isinstance(_A ,  _A  )
						assert dataset.num_rows == 4
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_1", "col_2", "col_3"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype





@pytest.mark.parametrize('''keep_in_memory''' ,  [False, True]  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												lowerCAmelCase_      			=  JsonDatasetReader(_A ,  cache_dir=_A ,  keep_in_memory=_A  ).read()
						_check_json_dataset(_A ,  _A  )





@pytest.mark.parametrize(
    '''features''' ,  [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ] ,  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						lowerCAmelCase_      			=  features.copy() if features else default_expected_features
						lowerCAmelCase_      			=  (
						    Features({feature: Value(_A  ) for feature, dtype in features.items()}  ) if features is not None else None
						)
						lowerCAmelCase_      			=  JsonDatasetReader(_A ,  features=_A ,  cache_dir=_A  ).read()
						_check_json_dataset(_A ,  _A  )





@pytest.mark.parametrize(
    '''features''' ,  [
        None,
        {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''},
    ] ,  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}
						lowerCAmelCase_      			=  features.copy() if features else default_expected_features
						lowerCAmelCase_      			=  (
						    Features({feature: Value(_A  ) for feature, dtype in features.items()}  ) if features is not None else None
						)
						lowerCAmelCase_      			=  JsonDatasetReader(_A ,  features=_A ,  cache_dir=_A  ).read()
						assert isinstance(_A ,  _A  )
						assert dataset.num_rows == 2
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_3", "col_1", "col_2"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype





def __UpperCamelCase			(       _A ,  _A  ):
						# jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"}
						lowerCAmelCase_      			=  {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''}
						lowerCAmelCase_      			=  features.copy()
						lowerCAmelCase_      			=  (
						    Features({feature: Value(_A  ) for feature, dtype in features.items()}  ) if features is not None else None
						)
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  JsonDatasetReader(_A ,  features=_A ,  cache_dir=_A  ).read()
						assert isinstance(_A ,  _A  )
						assert dataset.num_rows == 2
						assert dataset.num_columns == 3
						assert dataset.column_names == ["col_2", "col_3", "col_1"]
						for feature, expected_dtype in expected_features.items():
												assert dataset.features[feature].dtype == expected_dtype





@pytest.mark.parametrize('''split''' ,  [None, NamedSplit('''train'''  ), '''train''', '''test''']  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						lowerCAmelCase_      			=  JsonDatasetReader(_A ,  cache_dir=_A ,  split=_A  ).read()
						_check_json_dataset(_A ,  _A  )
						assert dataset.split == split if split else "train"





@pytest.mark.parametrize('''path_type''' ,  [str, list]  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						if issubclass(_A ,  _A  ):
												lowerCAmelCase_      			=  jsonl_path
						elif issubclass(_A ,  _A  ):
												lowerCAmelCase_      			=  [jsonl_path]
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						lowerCAmelCase_      			=  JsonDatasetReader(_A ,  cache_dir=_A  ).read()
						_check_json_dataset(_A ,  _A  )





def __UpperCamelCase			(       _A ,  _A ,  _A=("train",)  ):
						assert isinstance(_A ,  _A  )
						for split in splits:
												lowerCAmelCase_      			=  dataset_dict[split]
												assert dataset.num_rows == 4
												assert dataset.num_columns == 3
												assert dataset.column_names == ["col_1", "col_2", "col_3"]
												for feature, expected_dtype in expected_features.items():
																		assert dataset.features[feature].dtype == expected_dtype





@pytest.mark.parametrize('''keep_in_memory''' ,  [False, True]  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
												lowerCAmelCase_      			=  JsonDatasetReader({'''train''': jsonl_path} ,  cache_dir=_A ,  keep_in_memory=_A  ).read()
						_check_json_datasetdict(_A ,  _A  )





@pytest.mark.parametrize(
    '''features''' ,  [
        None,
        {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''},
        {'''col_1''': '''string''', '''col_2''': '''string''', '''col_3''': '''string'''},
        {'''col_1''': '''int32''', '''col_2''': '''int32''', '''col_3''': '''int32'''},
        {'''col_1''': '''float32''', '''col_2''': '''float32''', '''col_3''': '''float32'''},
    ] ,  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						lowerCAmelCase_      			=  features.copy() if features else default_expected_features
						lowerCAmelCase_      			=  (
						    Features({feature: Value(_A  ) for feature, dtype in features.items()}  ) if features is not None else None
						)
						lowerCAmelCase_      			=  JsonDatasetReader({'''train''': jsonl_path} ,  features=_A ,  cache_dir=_A  ).read()
						_check_json_datasetdict(_A ,  _A  )





@pytest.mark.parametrize('''split''' ,  [None, NamedSplit('''train'''  ), '''train''', '''test''']  )
def __UpperCamelCase			(       _A ,  _A ,  _A  ):
						if split:
												lowerCAmelCase_      			=  {split: jsonl_path}
						else:
												lowerCAmelCase_      			=  '''train'''
												lowerCAmelCase_      			=  {'''train''': jsonl_path, '''test''': jsonl_path}
						lowerCAmelCase_      			=  tmp_path / '''cache'''
						lowerCAmelCase_      			=  {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''}
						lowerCAmelCase_      			=  JsonDatasetReader(_A ,  cache_dir=_A  ).read()
						_check_json_datasetdict(_A ,  _A ,  splits=list(path.keys()  )  )
						assert all(dataset[split].split == split for split in path.keys()  )





def __UpperCamelCase			(       _A  ):
						return json.load(_A  )





def __UpperCamelCase			(       _A  ):
						return [json.loads(_A  ) for line in buffer]






class  A		:



		@pytest.mark.parametrize('''lines, load_json_function''',	[(True, load_json_lines), (False, load_json)]   )
		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								with io.BytesIO() as buffer:
														JsonDatasetWriter(UpperCamelCase__,	UpperCamelCase__,	lines=UpperCamelCase__   ).write()
														buffer.seek(0   )
														lowerCAmelCase_      			=  load_json_function(UpperCamelCase__   )
								assert isinstance(UpperCamelCase__,	UpperCamelCase__   )
								assert isinstance(exported_content[0],	UpperCamelCase__   )
								assert len(UpperCamelCase__   ) == 10



		@pytest.mark.parametrize(
		    '''orient, container, keys, len_at''',	[
		        ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
		        ('''split''', dict, {'''columns''', '''data'''}, '''data'''),
		        ('''index''', dict, set('''0123456789'''   ), None),
		        ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
		        ('''values''', list, None, None),
		        ('''table''', dict, {'''schema''', '''data'''}, '''data'''),
		    ],	)
		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								with io.BytesIO() as buffer:
														JsonDatasetWriter(UpperCamelCase__,	UpperCamelCase__,	lines=UpperCamelCase__,	orient=UpperCamelCase__   ).write()
														buffer.seek(0   )
														lowerCAmelCase_      			=  load_json(UpperCamelCase__   )
								assert isinstance(UpperCamelCase__,	UpperCamelCase__   )
								if keys:
														if container is dict:
																				assert exported_content.keys() == keys
														else:
																				assert exported_content[0].keys() == keys
								else:
														assert not hasattr(UpperCamelCase__,	'''keys'''   ) and not hasattr(exported_content[0],	'''keys'''   )
								if len_at:
														assert len(exported_content[len_at]   ) == 10
								else:
														assert len(UpperCamelCase__   ) == 10



		@pytest.mark.parametrize('''lines, load_json_function''',	[(True, load_json_lines), (False, load_json)]   )
		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								with io.BytesIO() as buffer:
														JsonDatasetWriter(UpperCamelCase__,	UpperCamelCase__,	lines=UpperCamelCase__,	num_proc=2   ).write()
														buffer.seek(0   )
														lowerCAmelCase_      			=  load_json_function(UpperCamelCase__   )
								assert isinstance(UpperCamelCase__,	UpperCamelCase__   )
								assert isinstance(exported_content[0],	UpperCamelCase__   )
								assert len(UpperCamelCase__   ) == 10



		@pytest.mark.parametrize(
		    '''orient, container, keys, len_at''',	[
		        ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None),
		        ('''split''', dict, {'''columns''', '''data'''}, '''data'''),
		        ('''index''', dict, set('''0123456789'''   ), None),
		        ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''),
		        ('''values''', list, None, None),
		        ('''table''', dict, {'''schema''', '''data'''}, '''data'''),
		    ],	)
		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								with io.BytesIO() as buffer:
														JsonDatasetWriter(UpperCamelCase__,	UpperCamelCase__,	lines=UpperCamelCase__,	orient=UpperCamelCase__,	num_proc=2   ).write()
														buffer.seek(0   )
														lowerCAmelCase_      			=  load_json(UpperCamelCase__   )
								assert isinstance(UpperCamelCase__,	UpperCamelCase__   )
								if keys:
														if container is dict:
																				assert exported_content.keys() == keys
														else:
																				assert exported_content[0].keys() == keys
								else:
														assert not hasattr(UpperCamelCase__,	'''keys'''   ) and not hasattr(exported_content[0],	'''keys'''   )
								if len_at:
														assert len(exported_content[len_at]   ) == 10
								else:
														assert len(UpperCamelCase__   ) == 10



		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__   ):







								"""simple docstring"""



								with pytest.raises(UpperCamelCase__   ):
														with io.BytesIO() as buffer:
																				JsonDatasetWriter(UpperCamelCase__,	UpperCamelCase__,	num_proc=0   )







		@pytest.mark.parametrize('''compression, extension''',	[('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')]   )
		def        SCREAMING_SNAKE_CASE__			(     self,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__,	UpperCamelCase__   ):







								"""simple docstring"""



								lowerCAmelCase_      			=  tmp_path_factory.mktemp('''data'''   ) / f"test.json.{extension}"
								lowerCAmelCase_      			=  str(shared_datadir / f"test_file.json.{extension}"   )
								JsonDatasetWriter(UpperCamelCase__,	UpperCamelCase__,	compression=UpperCamelCase__   ).write()

								with fsspec.open(UpperCamelCase__,	'''rb''',	compression='''infer'''   ) as f:
														lowerCAmelCase_      			=  f.read()
								with fsspec.open(UpperCamelCase__,	'''rb''',	compression='''infer'''   ) as f:
														lowerCAmelCase_      			=  f.read()
								assert exported_content == original_content




