




import inspect
import os
import unittest
from pathlib import Path

import torch

import accelerate
from accelerate.test_utils import execute_subprocess_async
from accelerate.test_utils.testing import run_command


class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			UpperCamelCase__								=inspect.getfile(accelerate.test_utils						)
			UpperCamelCase__								=os.path.sep.join(mod_file.split(os.path.sep						)[:-1] + ['''scripts''', '''test_cli.py''']						)

			UpperCamelCase__								=['''accelerate''', '''launch''']
			UpperCamelCase__								=Path.home() / '''.cache/huggingface/accelerate'''
			UpperCamelCase__								='''default_config.yaml'''
			UpperCamelCase__								=config_folder / config_file
			UpperCamelCase__								=config_folder / '''_default_config.yaml'''

			UpperCamelCase__								=Path('''tests/test_configs'''						)

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   Optional[int]  )						->   int:
								if cls.config_path.is_file():
													cls.config_path.rename(cls.changed_path  )

			@classmethod
			def 							UpperCAmelCase__       ( cls			:   Dict  )						->   List[str]:
								if cls.changed_path.is_file():
													cls.changed_path.rename(cls.config_path  )

			def 							UpperCAmelCase__       ( self			:   str  )						->   Optional[Any]:
								__magic_name__							:	Dict    							=							self.base_cmd
								if torch.cuda.is_available() and (torch.cuda.device_count() > 1):
													cmd += ["--multi_gpu"]
								execute_subprocess_async(cmd + [self.test_file_path]       ,						env=os.environ.copy()  )

			def 							UpperCAmelCase__       ( self			:   int  )						->   Optional[int]:
								for config in sorted(self.test_config_path.glob('''**/*.yaml'''  )  ):
													with self.subTest(config_file=lowerCamelCase_  ):
																		execute_subprocess_async(
																		    self.base_cmd + ['''--config_file''', str(lowerCamelCase_  ), self.test_file_path]       ,						env=os.environ.copy()  )


			def 							UpperCAmelCase__       ( self			:   int  )						->   Union[str, Any]:
								execute_subprocess_async(['''accelerate''', '''test''']       ,						env=os.environ.copy()  )






class    lowerCamelCase    (		unittest.TestCase						):






			'''simple docstring'''





			UpperCamelCase__								='''test-tpu'''
			UpperCamelCase__								='''us-central1-a'''
			UpperCamelCase__								='''ls'''
			UpperCamelCase__								=['''accelerate''', '''tpu-config''']
			UpperCamelCase__								='''cd /usr/share'''
			UpperCamelCase__								='''tests/test_samples/test_command_file.sh'''
			UpperCamelCase__								='''Running gcloud compute tpus tpu-vm ssh'''

			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Optional[Any]:
								__magic_name__							:	str    							=							run_command(
								    self.cmd
								    + ['''--command''', self.command, '''--tpu_zone''', self.tpu_zone, '''--tpu_name''', self.tpu_name, '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Union[str, Any]  )						->   int:
								__magic_name__							:	int    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/0_12_0.yaml''',
								        '''--command''',
								        self.command,
								        '''--tpu_zone''',
								        self.tpu_zone,
								        '''--tpu_name''',
								        self.tpu_name,
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   Tuple:
								__magic_name__							:	Any    							=							run_command(
								    self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--debug''']       ,						return_stdout=lowerCamelCase_  )
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Optional[int]  )						->   Tuple:
								__magic_name__							:	Tuple    							=							run_command(
								    self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command''', self.command, '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   List[Any]  )						->   Dict:
								__magic_name__							:	str    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/latest.yaml''',
								        '''--command''',
								        self.command,
								        '''--command''',
								        '''echo "Hello World"''',
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; ls; echo "Hello World" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   Optional[int]:
								__magic_name__							:	Union[str, Any]    							=							run_command(
								    self.cmd
								    + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--command_file''', self.command_file, '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   int  )						->   List[Any]:
								__magic_name__							:	List[Any]    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/0_12_0.yaml''',
								        '''--command_file''',
								        self.command_file,
								        '''--tpu_zone''',
								        self.tpu_zone,
								        '''--tpu_name''',
								        self.tpu_name,
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)

			def 							UpperCAmelCase__       ( self			:   str  )						->   Dict:
								__magic_name__							:	Tuple    							=							run_command(
								    self.cmd + ['''--config_file''', '''tests/test_configs/latest.yaml''', '''--install_accelerate''', '''--debug''']       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate -U; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)


			def 							UpperCAmelCase__       ( self			:   Any  )						->   Tuple:
								__magic_name__							:	Tuple    							=							run_command(
								    self.cmd
								    + [
								        '''--config_file''',
								        '''tests/test_configs/latest.yaml''',
								        '''--install_accelerate''',
								        '''--accelerate_version''',
								        '''12.0.0''',
								        '''--debug''',
								    ]       ,						return_stdout=lowerCamelCase_       ,						)
								self.assertIn(
								    F'''{self.gcloud} test-tpu --zone us-central1-a --command {self.base_output}; pip install accelerate==12.0.0; echo "hello world"; echo "this is a second command" --worker all'''       ,						lowerCamelCase_       ,						)









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    lowerCamelCase    (		_lowerCamelCase						):






			'''simple docstring'''





			def __init__( self			:   List[Any]       ,						lowerCamelCase_			:   NestedDataStructureLike[PathLike]       ,						lowerCamelCase_			:   Optional[NamedSplit] = None       ,						lowerCamelCase_			:   Optional[Features] = None       ,						lowerCamelCase_			:   str = None       ,						lowerCamelCase_			:   bool = False       ,						lowerCamelCase_			:   bool = False       ,						lowerCamelCase_			:   Optional[str] = None       ,						lowerCamelCase_			:   Optional[int] = None       ,						**lowerCamelCase_			:   str       ,						)						->   Dict:
								super().__init__(
								    lowerCamelCase_       ,						split=lowerCamelCase_       ,						features=lowerCamelCase_       ,						cache_dir=lowerCamelCase_       ,						keep_in_memory=lowerCamelCase_       ,						streaming=lowerCamelCase_       ,						num_proc=lowerCamelCase_       ,						**lowerCamelCase_       ,						)
								__magic_name__							:	Optional[int]    							=							field
								__magic_name__							:	Optional[Any]    							=							path_or_paths if isinstance(lowerCamelCase_       ,						lowerCamelCase_  ) else {self.split: path_or_paths}
								__magic_name__							:	Optional[Any]    							=							Json(
								    cache_dir=lowerCamelCase_       ,						data_files=lowerCamelCase_       ,						features=lowerCamelCase_       ,						field=lowerCamelCase_       ,						**lowerCamelCase_       ,						)


			def 							UpperCAmelCase__       ( self			:   Optional[Any]  )						->   List[str]:
								# Build iterable dataset
								if self.streaming:
													__magic_name__							:	Optional[Any]    							=							self.builder.as_streaming_dataset(split=self.split  )
								# Build regular (map-style) dataset
								else:
													__magic_name__							:	int    							=							None
													__magic_name__							:	Tuple    							=							None
													__magic_name__							:	Tuple    							=							None
													__magic_name__							:	Optional[int]    							=							None

													self.builder.download_and_prepare(
													    download_config=lowerCamelCase_       ,						download_mode=lowerCamelCase_       ,						verification_mode=lowerCamelCase_       ,						base_path=lowerCamelCase_       ,						num_proc=self.num_proc       ,						)
													__magic_name__							:	Any    							=							self.builder.as_dataset(
													    split=self.split       ,						verification_mode=lowerCamelCase_       ,						in_memory=self.keep_in_memory  )
								return dataset






class    lowerCamelCase    :






			'''simple docstring'''





			def __init__( self			:   int       ,						lowerCamelCase_			:   Dataset       ,						lowerCamelCase_			:   Union[PathLike, BinaryIO]       ,						lowerCamelCase_			:   Optional[int] = None       ,						lowerCamelCase_			:   Optional[int] = None       ,						**lowerCamelCase_			:   List[Any]       ,						)						->   List[Any]:
								if num_proc is not None and num_proc <= 0:
													raise ValueError(F'''num_proc {num_proc} must be an integer > 0.'''  )

								__magic_name__							:	Optional[Any]    							=							dataset
								__magic_name__							:	Tuple    							=							path_or_buf
								__magic_name__							:	Dict    							=							batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
								__magic_name__							:	Any    							=							num_proc
								__magic_name__							:	Tuple    							=							'''utf-8'''
								__magic_name__							:	Tuple    							=							to_json_kwargs

			def 							UpperCAmelCase__       ( self			:   Dict  )						->   int:
								__magic_name__							:	int    							=							self.to_json_kwargs.pop('''path_or_buf'''       ,						lowerCamelCase_  )
								__magic_name__							:	Any    							=							self.to_json_kwargs.pop('''orient'''       ,						'''records'''  )
								__magic_name__							:	List[Any]    							=							self.to_json_kwargs.pop('''lines'''       ,						True if orient == '''records''' else False  )
								__magic_name__							:	Optional[int]    							=							self.to_json_kwargs.pop('''index'''       ,						False if orient in ['''split''', '''table'''] else True  )
								__magic_name__							:	List[str]    							=							self.to_json_kwargs.pop('''compression'''       ,						lowerCamelCase_  )

								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=lowerCamelCase_  ) as buffer:
																		__magic_name__							:	str    							=							self._write(file_obj=lowerCamelCase_       ,						orient=lowerCamelCase_       ,						lines=lowerCamelCase_       ,						index=lowerCamelCase_       ,						**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.'''  )
													__magic_name__							:	List[str]    							=							self._write(
													    file_obj=self.path_or_buf       ,						orient=lowerCamelCase_       ,						lines=lowerCamelCase_       ,						index=lowerCamelCase_       ,						**self.to_json_kwargs  )
								return written

			def 							UpperCAmelCase__       ( self			:   Optional[Any]       ,						lowerCamelCase_			:   Dict  )						->   Optional[int]:
								__magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__							:	Any    							=							args

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


			def 							UpperCAmelCase__       ( self			:   int       ,						lowerCamelCase_			:   BinaryIO       ,						lowerCamelCase_			:   List[str]       ,						lowerCamelCase_			:   Union[str, Any]       ,						lowerCamelCase_			:   Any       ,						**lowerCamelCase_			:   Optional[Any]       ,						)						->   int:
								__magic_name__							:	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'''       ,						):
																		__magic_name__							:	List[str]    							=							self._batch_json((offset, orient, lines, index, to_json_kwargs)  )
																		written += file_obj.write(lowerCamelCase_  )
								else:
													__magic_name__							,    __magic_name__							:	Optional[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       ,						lowerCamelCase_       ,						lowerCamelCase_  )]       ,						)       ,						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(lowerCamelCase_  )

								return written



