






'''simple docstring'''
import importlib
import os

import fsspec
import pytest
from fsspec import register_implementation
from fsspec.registry import _registry as _fsspec_registry

from datasets.filesystems import COMPRESSION_FILESYSTEMS, HfFileSystem, extract_path_from_uri, is_remote_filesystem

from .utils import require_lza, require_zstandard




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




   assert "mock" in _fsspec_registry
   assert "bz2" in _fsspec_registry




def 		__SCREAMING_SNAKE_CASE					(  ):


   """simple docstring"""




   assert "mock" not in _fsspec_registry
   assert "bz2" in _fsspec_registry




def 		__SCREAMING_SNAKE_CASE					(  ):


   """simple docstring"""




   lowercase_	:    Optional[Any]           =     "mock-s3-bucket"
   lowercase_	:    Any           =     F"""s3://{mock_bucket}"""
   lowercase_	:    int           =     extract_path_from_uri(_UpperCamelCase							)
   assert dataset_path.startswith("s3://"							) is False

   lowercase_	:    str           =     "./local/path"
   lowercase_	:    int           =     extract_path_from_uri(_UpperCamelCase							)
   assert dataset_path == new_dataset_path




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase							):


   """simple docstring"""




   lowercase_	:    List[Any]           =     is_remote_filesystem(_UpperCamelCase							)
   assert is_remote is True

   lowercase_	:    str           =     fsspec.filesystem("file"							)

   lowercase_	:    List[Any]           =     is_remote_filesystem(_UpperCamelCase							)
   assert is_remote is False




@pytest.mark.parametrize("compression_fs_class"						,		_UpperCamelCase							)
def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase							):


   """simple docstring"""




   lowercase_	:    List[str]           =     {"gzip": gz_file, "xz": xz_file, "zstd": zstd_file, "bz2": bza_file, "lz4": lza_file}
   lowercase_	:    Any           =     input_paths[compression_fs_class.protocol]
   if input_path is None:
      lowercase_	:    Dict           =     F"""for '{compression_fs_class.protocol}' compression protocol, """
      if compression_fs_class.protocol == "lz4":
         reason += require_lza.kwargs["reason"]
      elif compression_fs_class.protocol == "zstd":
         reason += require_zstandard.kwargs["reason"]
      pytest.skip(_UpperCamelCase							)
   lowercase_	:    List[str]           =     fsspec.filesystem(compression_fs_class.protocol						,		fo=_UpperCamelCase							)
   assert isinstance(_UpperCamelCase						,		_UpperCamelCase							)
   lowercase_	:    Optional[Any]           =     os.path.basename(_UpperCamelCase							)
   lowercase_	:    str           =     expected_filename[: expected_filename.rindex("."							)]
   assert fs.glob("*"							) == [expected_filename]
   with fs.open(_UpperCamelCase						,		"r"						,		encoding="utf-8"							) as f, open(_UpperCamelCase						,		encoding="utf-8"							) as expected_file:
      assert f.read() == expected_file.read()




@pytest.mark.parametrize("protocol"						,		["zip", "gzip"]							)
def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase							):


   """simple docstring"""




   lowercase_	:    Any           =     {"zip": zip_jsonl_path, "gzip": jsonl_gz_path}
   lowercase_	:    str           =     compressed_file_paths[protocol]
   lowercase_	:    Any           =     "dataset.jsonl"
   lowercase_	:    Dict           =     F"""{protocol}://{member_file_path}::{compressed_file_path}"""
   lowercase_	:    List[Any]           =     fsspec.get_fs_token_paths(_UpperCamelCase							)
   assert fs.isfile(_UpperCamelCase							)
   assert not fs.isfile("non_existing_" + member_file_path							)




@pytest.mark.integration
def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase							):


   """simple docstring"""




   lowercase_	:    int           =     hf_api.dataset_info(_UpperCamelCase						,		token=_UpperCamelCase							)
   lowercase_	:    Optional[Any]           =     HfFileSystem(repo_info=_UpperCamelCase						,		token=_UpperCamelCase							)
   assert sorted(hffs.glob("*"							)							) == [".gitattributes", "data"]
   assert hffs.isdir("data"							)
   assert hffs.isfile(".gitattributes"							) and hffs.isfile("data/text_data.txt"							)
   with open(_UpperCamelCase							) as f:
      assert hffs.open("data/text_data.txt"						,		"r"							).read() == f.read()





def 		__SCREAMING_SNAKE_CASE					(  ):


   """simple docstring"""




   lowercase_	:    List[Any]           =     "bz2"

   # Import module
   import datasets.filesystems

   # Overwrite protocol and reload
   register_implementation(_UpperCamelCase						,		_UpperCamelCase						,		clobber=_UpperCamelCase							)
   with pytest.warns(_UpperCamelCase							) as warning_info:
      importlib.reload(datasets.filesystems							)

   assert len(_UpperCamelCase							) == 1
   assert (
       str(warning_info[0].message							)
       == F"""A filesystem protocol was already set for {protocol} and will be overwritten."""
   )












'''simple docstring'''
import multiprocessing
import os
from typing import BinaryIO, Optional, Union

import fsspec

from .. import Dataset, Features, NamedSplit, config
from ..formatting import query_table
from ..packaged_modules.json.json import Json
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader


class        _UpperCAmelCase						(		snake_case			):




    def __init__(			self  :       Tuple  ,     a  :       NestedDataStructureLike[PathLike]  ,     a  :       Optional[NamedSplit] = None  ,     a  :       Optional[Features] = None  ,     a  :       str = None  ,     a  :       bool = False  ,     a  :       bool = False  ,     a  :       Optional[str] = None  ,     a  :       Optional[int] = None  ,     **a  :       List[Any]  ,     ):






       '''simple docstring'''






       super().__init__(
           a  ,     split=a  ,     features=a  ,     cache_dir=a  ,     keep_in_memory=a  ,     streaming=a  ,     num_proc=a  ,     **a  ,     )
       lowercase_	:    str           =     field
       lowercase_	:    Optional[Any]           =     path_or_paths if isinstance(a  ,     a			) else {self.split: path_or_paths}
       lowercase_	:    Any           =     Json(
           cache_dir=a  ,     data_files=a  ,     features=a  ,     field=a  ,     **a  ,     )





    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       if self.streaming:
          lowercase_	:    Any           =     self.builder.as_streaming_dataset(split=self.split			)
       # Build regular (map-style) dataset
       else:
          lowercase_	:    Dict           =     None
          lowercase_	:    Optional[int]           =     None
          lowercase_	:    str           =     None
          lowercase_	:    str           =     None

          self.builder.download_and_prepare(
              download_config=a  ,     download_mode=a  ,     verification_mode=a  ,     base_path=a  ,     num_proc=self.num_proc  ,     )
          lowercase_	:    int           =     self.builder.as_dataset(
              split=self.split  ,     verification_mode=a  ,     in_memory=self.keep_in_memory			)
       return dataset


class        _UpperCAmelCase						:




    def __init__(			self  :       str  ,     a  :       Dataset  ,     a  :       Union[PathLike, BinaryIO]  ,     a  :       Optional[int] = None  ,     a  :       Optional[int] = None  ,     **a  :       List[Any]  ,     ):






       '''simple docstring'''






       if num_proc is not None and num_proc <= 0:
          raise ValueError(f"""num_proc {num_proc} must be an integer > 0."""			)

       lowercase_	:    Dict           =     dataset
       lowercase_	:    Optional[int]           =     path_or_buf
       lowercase_	:    List[Any]           =     batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
       lowercase_	:    Optional[Any]           =     num_proc
       lowercase_	:    List[Any]           =     "utf-8"
       lowercase_	:    List[str]           =     to_json_kwargs




    def 				lowerCAmelCase__				(			self  :       Optional[int]			):






       '''simple docstring'''






       lowercase_	:    str           =     self.to_json_kwargs.pop("path_or_buf"  ,     a			)
       lowercase_	:    Any           =     self.to_json_kwargs.pop("orient"  ,     "records"			)
       lowercase_	:    Any           =     self.to_json_kwargs.pop("lines"  ,     True if orient == "records" else False			)
       lowercase_	:    List[str]           =     self.to_json_kwargs.pop("index"  ,     False if orient in ["split", "table"] else True			)
       lowercase_	:    int           =     self.to_json_kwargs.pop("compression"  ,     a			)

       if compression not in [None, "infer", "gzip", "bz2", "xz"]:
          raise NotImplementedError(f"""`datasets` currently does not support {compression} compression"""			)

       if isinstance(self.path_or_buf  ,     (str, bytes, os.PathLike)			):
          with fsspec.open(self.path_or_buf  ,     "wb"  ,     compression=a			) as buffer:
             lowercase_	:    Dict           =     self._write(file_obj=a  ,     orient=a  ,     lines=a  ,     index=a  ,     **self.to_json_kwargs			)
       else:
          if compression:
             raise NotImplementedError(
                 f"""The compression parameter is not supported when writing to a buffer, but compression={compression}"""
                 " was passed. Please provide a local path instead."			)
          lowercase_	:    Dict           =     self._write(
              file_obj=self.path_or_buf  ,     orient=a  ,     lines=a  ,     index=a  ,     **self.to_json_kwargs			)
       return written




    def 				lowerCAmelCase__				(			self  :       Optional[int]  ,     a  :       List[str]			):






       '''simple docstring'''






       lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_    ,		lowercase_	:    List[Any]           =     args

       lowercase_	:    Optional[int]           =     query_table(
           table=self.dataset.data  ,     key=slice(a  ,     offset + self.batch_size			)  ,     indices=self.dataset._indices  ,     )
       lowercase_	:    Dict           =     batch.to_pandas().to_json(
           path_or_buf=a  ,     orient=a  ,     lines=a  ,     index=a  ,     **a			)
       if not json_str.endswith("\n"			):
          json_str += "\n"
       return json_str.encode(self.encoding			)





    def 				lowerCAmelCase__				(			self  :       int  ,     a  :       BinaryIO  ,     a  :       int  ,     a  :       str  ,     a  :       Union[str, Any]  ,     **a  :       str  ,     ):






       '''simple docstring'''






       lowercase_	:    Union[str, Any]           =     0

       if self.num_proc is None or self.num_proc == 1:
          for offset in logging.tqdm(
              range(0  ,     len(self.dataset			)  ,     self.batch_size			)  ,     unit="ba"  ,     disable=not logging.is_progress_bar_enabled()  ,     desc="Creating json from Arrow format"  ,     ):
             lowercase_	:    Dict           =     self._batch_json((offset, orient, lines, index, to_json_kwargs)			)
             written += file_obj.write(a			)
       else:
          lowercase_    ,		lowercase_	:    Any           =     len(self.dataset			), self.batch_size
          with multiprocessing.Pool(self.num_proc			) as pool:
             for json_str in logging.tqdm(
                 pool.imap(
                     self._batch_json  ,     [(offset, orient, lines, index, to_json_kwargs) for offset in range(0  ,     a  ,     a			)]  ,     )  ,     total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size  ,     unit="ba"  ,     disable=not logging.is_progress_bar_enabled()  ,     desc="Creating json from Arrow format"  ,     ):
                written += file_obj.write(a			)

       return written




