






'''simple docstring'''





import multiprocessing
import os
from typing import BinaryIO, Optional, Union

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





class 		SCREAMING_SNAKE_CASE__   (     lowercase_    ):



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






								'''simple docstring'''


								super().__init__(
								    a				,   split=a				,   features=a				,   cache_dir=a				,   keep_in_memory=a				,   streaming=a				,   num_proc=a				,   **a				,   )
								a_				     =   path_or_paths if isinstance(a				,   a) else {self.split: path_or_paths}
								a_				     =   Csv(
								    cache_dir=a				,   data_files=a				,   features=a				,   **a				,   )




		def _lowerCAmelCase     (    self:    Union[str, Any])  ->Optional[Any]:






								'''simple docstring'''


								if self.streaming:
														a_				     =   self.builder.as_streaming_dataset(split=self.split)
								# Build regular (map-style) dataset
								else:
														a_				     =   None
														a_				     =   None
														a_				     =   None
														a_				     =   None

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





class 		SCREAMING_SNAKE_CASE__   :



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






								'''simple docstring'''


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

								a_				     =   dataset
								a_				     =   path_or_buf
								a_				     =   batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
								a_				     =   num_proc
								a_				     =   "utf-8"
								a_				     =   to_csv_kwargs



		def _lowerCAmelCase     (    self:    int)  ->int:






								'''simple docstring'''


								a_				     =   self.to_csv_kwargs.pop("path_or_buf"				,   a)
								a_				     =   self.to_csv_kwargs.pop("header"				,   a)
								a_				     =   self.to_csv_kwargs.pop("index"				,   a)

								if isinstance(self.path_or_buf				,   (str, bytes, os.PathLike)):
														with open(self.path_or_buf				,   "wb+") as buffer:
																				a_				     =   self._write(file_obj=a				,   header=a				,   index=a				,   **self.to_csv_kwargs)
								else:
														a_				     =   self._write(file_obj=self.path_or_buf				,   header=a				,   index=a				,   **self.to_csv_kwargs)
								return written



		def _lowerCAmelCase     (    self:    Tuple				,   a:    List[str])  ->str:






								'''simple docstring'''


								a_     ,       a_     ,       a_     ,       a_				     =   args

								a_				     =   query_table(
								    table=self.dataset.data				,   key=slice(a				,   offset + self.batch_size)				,   indices=self.dataset._indices				,   )
								a_				     =   batch.to_pandas().to_csv(
								    path_or_buf=a				,   header=header if (offset == 0) else False				,   index=a				,   **a)
								return csv_str.encode(self.encoding)




		def _lowerCAmelCase     (    self:    List[Any]				,   a:    BinaryIO				,   a:    List[Any]				,   a:    Optional[int]				,   **a:    List[str])  ->int:






								'''simple docstring'''


								a_				     =   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 CSV from Arrow format"				,   ):
																				a_				     =   self._batch_csv((offset, header, index, to_csv_kwargs))
																				written += file_obj.write(a)

								else:
														a_     ,       a_				     =   len(self.dataset), self.batch_size
														with multiprocessing.Pool(self.num_proc) as pool:
																				for csv_str in logging.tqdm(
																				    pool.imap(
																				        self._batch_csv				,   [(offset, header, index, to_csv_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 CSV from Arrow format"				,   ):
																										written += file_obj.write(a)

								return written











'''simple docstring'''





from typing import List, Optional, Tuple, Union

from . import logging
from .import_utils import is_torch_available, is_torch_version


if is_torch_available():
							import torch

a_      = logging.get_logger(__name__)  # pylint: disable=invalid-name

try:
							from torch._dynamo import allow_in_graph as maybe_allow_in_graph
except (ImportError, ModuleNotFoundError):



							def 			__UpperCAmelCase				(cls				)		->				Optional[Any]:

													'''simple docstring'''


													return cls



def 			__UpperCAmelCase				(lowercase__	,lowercase__ = None	,lowercase__ = None	,lowercase__ = None	,lowercase__ = None	,)		->				Union[str, Any]:

						'''simple docstring'''


						a_				     =   device
						a_				     =   shape[0]

						a_				     =   layout or torch.strided
						a_				     =   device or torch.device("cpu"				)

						if generator is not None:
												a_				     =   generator.device.type if not isinstance(lowercase__	,lowercase__				) else generator[0].device.type
												if gen_device_type != device.type and gen_device_type == "cpu":
																		a_				     =   "cpu"
																		if device != "mps":
																								logger.info(
																								    F"""The passed generator was created on 'cpu' even though a tensor on {device} was expected."""
																								    F""" Tensors will be created on 'cpu' and then moved to {device}. Note that one can probably"""
																								    F""" slighly speed up this function by passing a generator that was created on the {device} device."""				)
												elif gen_device_type != device.type and gen_device_type == "cuda":
																		raise ValueError(F"""Cannot generate a {device} tensor from a generator of type {gen_device_type}."""				)

						if isinstance(lowercase__	,lowercase__				):
												a_				     =   (1,) + shape[1:]
												a_				     =   [
												    torch.randn(lowercase__	,generator=generator[i]	,device=lowercase__	,dtype=lowercase__	,layout=lowercase__				)
												    for i in range(lowercase__				)
												]
												a_				     =   torch.cat(lowercase__	,dim=0				).to(lowercase__				)
						else:
												a_				     =   torch.randn(lowercase__	,generator=lowercase__	,device=lowercase__	,dtype=lowercase__	,layout=lowercase__				).to(lowercase__				)

						return latents



def 			__UpperCAmelCase				(lowercase__				)		->				Tuple:

						'''simple docstring'''


						if is_torch_version("<"	,"2.0.0"				) or not hasattr(lowercase__	,"_dynamo"				):
												return False
						return isinstance(lowercase__	,torch._dynamo.eval_frame.OptimizedModule				)



