


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        SCREAMING_SNAKE_CASE_						(			__A :			List[str]  ,    __A :			Optional[Any]				)	->		Dict:

       """simple docstring"""

       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        SCREAMING_SNAKE_CASE_						(			__A :			Optional[Any]  ,    __A :			List[Any]  ,    __A :			Tuple				)	->		Optional[Any]:

       """simple docstring"""

       a_					:		Any							=  tmp_path / 'cache'
       a_					:		Optional[Any]							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
              a_					:		str							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Union[str, Any]  ,    __A :			Tuple  ,    __A :			Optional[int]				)	->		Dict:

       """simple docstring"""

       a_					:		Any							=  tmp_path / 'cache'
       a_					:		Optional[int]							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_					:		int							=  features.copy() if features else default_expected_features
       a_					:		str							=  (
           Features({feature: Value(__A				) for feature, dtype in features.items()}				) if features is not None else None
       )
       a_					:		Any							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Any  ,    __A :			List[Any]  ,    __A :			str				)	->		Any:

       """simple docstring"""

       a_					:		Tuple							=  tmp_path / 'cache'
       a_					:		str							=  {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}
       a_					:		Tuple							=  features.copy() if features else default_expected_features
       a_					:		str							=  (
           Features({feature: Value(__A				) for feature, dtype in features.items()}				) if features is not None else None
       )
       a_					:		List[str]							=  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        SCREAMING_SNAKE_CASE_						(			__A :			str  ,    __A :			List[str]				)	->		Any:

       """simple docstring"""

       a_					:		Dict							=  {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'}
       a_					:		Optional[Any]							=  features.copy()
       a_					:		List[str]							=  (
           Features({feature: Value(__A				) for feature, dtype in features.items()}				) if features is not None else None
       )
       a_					:		List[Any]							=  tmp_path / 'cache'
       a_					:		Any							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Tuple  ,    __A :			Optional[int]  ,    __A :			Any				)	->		List[Any]:

       """simple docstring"""

       a_					:		List[Any]							=  tmp_path / 'cache'
       a_					:		str							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_					:		str							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Any  ,    __A :			Optional[Any]  ,    __A :			Optional[int]				)	->		List[Any]:

       """simple docstring"""

       if issubclass(__A  ,    __A				):
              a_					:		Dict							=  jsonl_path
       elif issubclass(__A  ,    __A				):
              a_					:		Tuple							=  [jsonl_path]
       a_					:		List[str]							=  tmp_path / 'cache'
       a_					:		List[Any]							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_					:		int							=  JsonDatasetReader(__A  ,    cache_dir=__A				).read()
       _check_json_dataset(__A  ,    __A				)







def        SCREAMING_SNAKE_CASE_						(			__A :			int  ,    __A :			Tuple  ,    __A :			Tuple=("train",)				)	->		int:

       """simple docstring"""

       assert isinstance(__A  ,    __A				)
       for split in splits:
              a_					:		str							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Dict  ,    __A :			Dict  ,    __A :			Any				)	->		Union[str, Any]:

       """simple docstring"""

       a_					:		Any							=  tmp_path / 'cache'
       a_					:		str							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
              a_					:		List[Any]							=  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        SCREAMING_SNAKE_CASE_						(			__A :			str  ,    __A :			Any  ,    __A :			List[Any]				)	->		List[str]:

       """simple docstring"""

       a_					:		List[Any]							=  tmp_path / 'cache'
       a_					:		Optional[int]							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_					:		Union[str, Any]							=  features.copy() if features else default_expected_features
       a_					:		Tuple							=  (
           Features({feature: Value(__A				) for feature, dtype in features.items()}				) if features is not None else None
       )
       a_					:		Dict							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Dict  ,    __A :			str  ,    __A :			List[str]				)	->		Any:

       """simple docstring"""

       if split:
              a_					:		Union[str, Any]							=  {split: jsonl_path}
       else:
              a_					:		str							=  'train'
              a_					:		List[Any]							=  {'train': jsonl_path, 'test': jsonl_path}
       a_					:		Optional[Any]							=  tmp_path / 'cache'
       a_					:		Optional[Any]							=  {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}
       a_					:		Optional[int]							=  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        SCREAMING_SNAKE_CASE_						(			__A :			Union[str, Any]				)	->		Optional[int]:

       """simple docstring"""

       return json.load(__A				)







def        SCREAMING_SNAKE_CASE_						(			__A :			Tuple				)	->		Union[str, Any]:

       """simple docstring"""

       return [json.loads(__A				) for line in buffer]
class  SCREAMING_SNAKE_CASE__  :
      @pytest.mark.parametrize('lines, load_json_function'     ,							[(True, load_json_lines), (False, load_json)]     )
      def        SCREAMING_SNAKE_CASE							(       self				:       str     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     )		->			Dict:
             with io.BytesIO() as buffer:
                    JsonDatasetWriter(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							lines=SCREAMING_SNAKE_CASE__     ).write()
                    buffer.seek(0     )
                    a_					:		Union[str, Any]							=  load_json_function(SCREAMING_SNAKE_CASE__     )
             assert isinstance(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
             assert isinstance(exported_content[0]     ,							SCREAMING_SNAKE_CASE__     )
             assert len(SCREAMING_SNAKE_CASE__     ) == 1_0
      @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				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     )		->			Optional[Any]:
             with io.BytesIO() as buffer:
                    JsonDatasetWriter(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							lines=SCREAMING_SNAKE_CASE__     ,							orient=SCREAMING_SNAKE_CASE__     ).write()
                    buffer.seek(0     )
                    a_					:		List[Any]							=  load_json(SCREAMING_SNAKE_CASE__     )
             assert isinstance(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
             if keys:
                    if container is dict:
                           assert exported_content.keys() == keys
                    else:
                           assert exported_content[0].keys() == keys
             else:
                    assert not hasattr(SCREAMING_SNAKE_CASE__     ,							'keys'     ) and not hasattr(exported_content[0]     ,							'keys'     )
             if len_at:
                    assert len(exported_content[len_at]     ) == 1_0
             else:
                    assert len(SCREAMING_SNAKE_CASE__     ) == 1_0
      @pytest.mark.parametrize('lines, load_json_function'     ,							[(True, load_json_lines), (False, load_json)]     )
      def        SCREAMING_SNAKE_CASE							(       self				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       Any     )		->			Optional[int]:
             with io.BytesIO() as buffer:
                    JsonDatasetWriter(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							lines=SCREAMING_SNAKE_CASE__     ,							num_proc=2     ).write()
                    buffer.seek(0     )
                    a_					:		Optional[int]							=  load_json_function(SCREAMING_SNAKE_CASE__     )
             assert isinstance(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
             assert isinstance(exported_content[0]     ,							SCREAMING_SNAKE_CASE__     )
             assert len(SCREAMING_SNAKE_CASE__     ) == 1_0
      @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				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     ,							SCREAMING_SNAKE_CASE__				:       List[Any]     )		->			List[str]:
             with io.BytesIO() as buffer:
                    JsonDatasetWriter(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							lines=SCREAMING_SNAKE_CASE__     ,							orient=SCREAMING_SNAKE_CASE__     ,							num_proc=2     ).write()
                    buffer.seek(0     )
                    a_					:		str							=  load_json(SCREAMING_SNAKE_CASE__     )
             assert isinstance(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     )
             if keys:
                    if container is dict:
                           assert exported_content.keys() == keys
                    else:
                           assert exported_content[0].keys() == keys
             else:
                    assert not hasattr(SCREAMING_SNAKE_CASE__     ,							'keys'     ) and not hasattr(exported_content[0]     ,							'keys'     )
             if len_at:
                    assert len(exported_content[len_at]     ) == 1_0
             else:
                    assert len(SCREAMING_SNAKE_CASE__     ) == 1_0
      def        SCREAMING_SNAKE_CASE							(       self				:       Union[str, Any]     ,							SCREAMING_SNAKE_CASE__				:       Optional[Any]     )		->			Dict:
             with pytest.raises(SCREAMING_SNAKE_CASE__     ):
                    with io.BytesIO() as buffer:
                           JsonDatasetWriter(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							num_proc=0     )

      @pytest.mark.parametrize('compression, extension'     ,							[('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')]     )
      def        SCREAMING_SNAKE_CASE							(       self				:       List[str]     ,							SCREAMING_SNAKE_CASE__				:       Any     ,							SCREAMING_SNAKE_CASE__				:       Tuple     ,							SCREAMING_SNAKE_CASE__				:       Optional[int]     ,							SCREAMING_SNAKE_CASE__				:       str     ,							SCREAMING_SNAKE_CASE__				:       Union[str, Any]     )		->			Optional[int]:
             a_					:		Optional[int]							=  tmp_path_factory.mktemp('data'     ) / F"""test.json.{extension}"""
             a_					:		int							=  str(shared_datadir / F"""test_file.json.{extension}"""     )
             JsonDatasetWriter(SCREAMING_SNAKE_CASE__     ,							SCREAMING_SNAKE_CASE__     ,							compression=SCREAMING_SNAKE_CASE__     ).write()

             with fsspec.open(SCREAMING_SNAKE_CASE__     ,							'rb'     ,							compression='infer'     ) as f:
                    a_					:		Optional[Any]							=  f.read()
             with fsspec.open(SCREAMING_SNAKE_CASE__     ,							'rb'     ,							compression='infer'     ) as f:
                    a_					:		List[str]							=  f.read()
             assert exported_content == original_content






import inspect
import re
from hashlib import shaaaa
from typing import Dict, List

from .arrow import arrow
from .audiofolder import audiofolder
from .csv import csv
from .imagefolder import imagefolder
from .json import json
from .pandas import pandas
from .parquet import parquet
from .sql import sql  # noqa F401
from .text import text







def        SCREAMING_SNAKE_CASE_						(			__A :			List[str]				)	->		str:

       """simple docstring"""

       a_					:		Tuple							=  []
       for line in lines:
              a_					:		Any							=  re.sub(R'#.*'  ,    ''  ,    __A				)  # remove comments
              if line:
                     filtered_lines.append(__A				)
       a_					:		Tuple							=  '\n'.join(__A				)

       # Make a hash from all this code
       a_					:		Tuple							=  full_str.encode('utf-8'				)
       return shaaaa(__A				).hexdigest()


# get importable module names and hash for caching
UpperCAmelCase_      : List[Any]  					=       {
    'csv': (csv.__name__, _hash_python_lines(inspect.getsource(csv).splitlines())),
    'json': (json.__name__, _hash_python_lines(inspect.getsource(json).splitlines())),
    'pandas': (pandas.__name__, _hash_python_lines(inspect.getsource(pandas).splitlines())),
    'parquet': (parquet.__name__, _hash_python_lines(inspect.getsource(parquet).splitlines())),
    'arrow': (arrow.__name__, _hash_python_lines(inspect.getsource(arrow).splitlines())),
    'text': (text.__name__, _hash_python_lines(inspect.getsource(text).splitlines())),
    'imagefolder': (imagefolder.__name__, _hash_python_lines(inspect.getsource(imagefolder).splitlines())),
    'audiofolder': (audiofolder.__name__, _hash_python_lines(inspect.getsource(audiofolder).splitlines())),
}

# Used to infer the module to use based on the data files extensions
UpperCAmelCase_      : Dict  					=       {
    '.csv': ('csv', {}),
    '.tsv': ('csv', {'sep': '\t'}),
    '.json': ('json', {}),
    '.jsonl': ('json', {}),
    '.parquet': ('parquet', {}),
    '.arrow': ('arrow', {}),
    '.txt': ('text', {}),
}
_EXTENSION_TO_MODULE.update({ext: ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('imagefolder', {}) for ext in imagefolder.ImageFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext: ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
_EXTENSION_TO_MODULE.update({ext.upper(): ('audiofolder', {}) for ext in audiofolder.AudioFolder.EXTENSIONS})
UpperCAmelCase_      : Optional[int]  					=       {'imagefolder', 'audiofolder'}

# Used to filter data files based on extensions given a module name
UpperCAmelCase_      : Dict[str, List[str]]  					=       {}
for _ext, (_module, _) in _EXTENSION_TO_MODULE.items():
   _MODULE_TO_EXTENSIONS.setdefault(_module, []).append(_ext)

_MODULE_TO_EXTENSIONS["imagefolder"].append('.zip')
_MODULE_TO_EXTENSIONS["audiofolder"].append('.zip')


