





"""simple docstring"""
import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


__SCREAMING_SNAKE_CASE							:    str		=    datasets.utils.logging.get_logger(__name__)





@dataclass
class      __A     (datasets.BuilderConfig):





							'''simple docstring'''

							__lowercase:		Optional[datasets.Features]							      =    None
							__lowercase:		str							      =    "utf-8"
							__lowercase:		Optional[str]							      =    None
							__lowercase:		Optional[str]							      =    None
							__lowercase:		bool							      =    True  # deprecated
							__lowercase:		Optional[int]							      =    None  # deprecated
							__lowercase:		int							      =    10 << 20  # 10MB
							__lowercase:		Optional[bool]							      =    None





class      __A     (datasets.ArrowBasedBuilder):





							'''simple docstring'''

							__lowercase:		str							      =    JsonConfig



							def 		lowerCAmelCase       (				self							:      Optional[int]       )					->Tuple:



														"""simple docstring"""



														if self.config.block_size is not None:
																					logger.warning("""The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead"""       )
																					snake_case_           =		self.config.block_size
														if self.config.use_threads is not True:
																					logger.warning(
																					    """The JSON loader parameter `use_threads` is deprecated and doesn't have any effect anymore."""       )
														if self.config.newlines_in_values is not None:
																					raise ValueError("""The JSON loader parameter `newlines_in_values` is no longer supported"""       )
														return datasets.DatasetInfo(features=self.config.features       )



							def 		lowerCAmelCase       (				self							:      Union[str, Any]		,       UpperCAmelCase_							:      Union[str, Any]       )					->List[Any]:



														"""simple docstring"""



														if not self.config.data_files:
																					raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""       )
														snake_case_           =		dl_manager.download_and_extract(self.config.data_files       )
														if isinstance(UpperCAmelCase_		,       (str, list, tuple)       ):
																					snake_case_           =		data_files
																					if isinstance(UpperCAmelCase_		,       UpperCAmelCase_       ):
																												snake_case_           =		[files]
																					snake_case_           =		[dl_manager.iter_files(UpperCAmelCase_       ) for file in files]
																					return [datasets.SplitGenerator(name=datasets.Split.TRAIN		,       gen_kwargs={"""files""": files}       )]
														snake_case_           =		[]
														for split_name, files in data_files.items():
																					if isinstance(UpperCAmelCase_		,       UpperCAmelCase_       ):
																												snake_case_           =		[files]
																					snake_case_           =		[dl_manager.iter_files(UpperCAmelCase_       ) for file in files]
																					splits.append(datasets.SplitGenerator(name=UpperCAmelCase_		,       gen_kwargs={"""files""": files}       )       )
														return splits



							def 		lowerCAmelCase       (				self							:      Tuple		,       UpperCAmelCase_							:      pa.Table       )					->pa.Table:



														"""simple docstring"""



														if self.config.features is not None:
																					# adding missing columns
																					for column_name in set(self.config.features       ) - set(pa_table.column_names       ):
																												snake_case_           =		self.config.features.arrow_schema.field(UpperCAmelCase_       ).type
																												snake_case_           =		pa_table.append_column(UpperCAmelCase_		,       pa.array([None] * len(UpperCAmelCase_       )		,       type=UpperCAmelCase_       )       )
																					# more expensive cast to support nested structures with keys in a different order
																					# allows str <-> int/float or str to Audio for example
																					snake_case_           =		table_cast(UpperCAmelCase_		,       self.config.features.arrow_schema       )
														return pa_table



							def 		lowerCAmelCase       (				self							:      Optional[Any]		,       UpperCAmelCase_							:      str       )					->List[str]:



														"""simple docstring"""



														for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase_       )       ):
																					# If the file is one json object and if we need to look at the list of items in one specific field
																					if self.config.field is not None:
																												with open(UpperCAmelCase_		,       encoding=self.config.encoding		,       errors=self.config.encoding_errors       ) as f:
																																			snake_case_           =		json.load(UpperCAmelCase_       )

																												# We keep only the field we are interested in
																												snake_case_           =		dataset[self.config.field]

																												# We accept two format: a list of dicts or a dict of lists
																												if isinstance(UpperCAmelCase_		,       (list, tuple)       ):
																																			snake_case_           =		set().union(*[row.keys() for row in dataset]       )
																																			snake_case_           =		{col: [row.get(UpperCAmelCase_       ) for row in dataset] for col in keys}
																												else:
																																			snake_case_           =		dataset
																												snake_case_           =		pa.Table.from_pydict(UpperCAmelCase_       )
																												yield file_idx, self._cast_table(UpperCAmelCase_       )

																					# If the file has one json object per line
																					else:
																												with open(UpperCAmelCase_		,       """rb"""       ) as f:
																																			snake_case_           =		0
																																			# Use block_size equal to the chunk size divided by 32 to leverage multithreading
																																			# Set a default minimum value of 16kB if the chunk size is really small
																																			snake_case_           =		max(self.config.chunksize // 32		,       16 << 10       )
																																			snake_case_           =		(
																																			    self.config.encoding_errors if self.config.encoding_errors is not None else """strict"""
																																			)
																																			while True:
																																										snake_case_           =		f.read(self.config.chunksize       )
																																										if not batch:
																																																	break
																																										# Finish current line
																																										try:
																																																	batch += f.readline()
																																										except (AttributeError, io.UnsupportedOperation):
																																																	batch += readline(UpperCAmelCase_       )
																																										# PyArrow only accepts utf-8 encoded bytes
																																										if self.config.encoding != "utf-8":
																																																	snake_case_           =		batch.decode(self.config.encoding		,       errors=UpperCAmelCase_       ).encode("""utf-8"""       )
																																										try:
																																																	while True:
																																																								try:
																																																															snake_case_           =		paj.read_json(
																																																															    io.BytesIO(UpperCAmelCase_       )		,       read_options=paj.ReadOptions(block_size=UpperCAmelCase_       )       )
																																																															break
																																																								except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
																																																															if (
																																																															    isinstance(UpperCAmelCase_		,       pa.ArrowInvalid       )
																																																															    and "straddling" not in str(UpperCAmelCase_       )
																																																															    or block_size > len(UpperCAmelCase_       )
																																																															):
																																																																						raise
																																																															else:
																																																																						# Increase the block size in case it was too small.
																																																																						# The block size will be reset for the next file.
																																																																						logger.debug(
																																																																						    F"""Batch of {len(UpperCAmelCase_       )} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}."""       )
																																																																						block_size *= 2
																																										except pa.ArrowInvalid as e:
																																																	try:
																																																								with open(
																																																								    UpperCAmelCase_		,       encoding=self.config.encoding		,       errors=self.config.encoding_errors       ) as f:
																																																															snake_case_           =		json.load(UpperCAmelCase_       )
																																																	except json.JSONDecodeError:
																																																								logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_       )}: {e}"""       )
																																																								raise e
																																																	# If possible, parse the file as a list of json objects and exit the loop
																																																	if isinstance(UpperCAmelCase_		,       UpperCAmelCase_       ):  # list is the only sequence type supported in JSON
																																																								try:
																																																															snake_case_           =		set().union(*[row.keys() for row in dataset]       )
																																																															snake_case_           =		{col: [row.get(UpperCAmelCase_       ) for row in dataset] for col in keys}
																																																															snake_case_           =		pa.Table.from_pydict(UpperCAmelCase_       )
																																																								except (pa.ArrowInvalid, AttributeError) as e:
																																																															logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_       )}: {e}"""       )
																																																															raise ValueError(F"""Not able to read records in the JSON file at {file}."""       ) from None
																																																								yield file_idx, self._cast_table(UpperCAmelCase_       )
																																																								break
																																																	else:
																																																								logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase_       )}: {e}"""       )
																																																								raise ValueError(
																																																								    F"""Not able to read records in the JSON file at {file}. """
																																																								    F"""You should probably indicate the field of the JSON file containing your records. """
																																																								    F"""This JSON file contain the following fields: {str(list(dataset.keys()       )       )}. """
																																																								    F"""Select the correct one and provide it as `field='XXX'` to the dataset loading method. """       ) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																																										yield (file_idx, batch_idx), self._cast_table(UpperCAmelCase_       )
																																										batch_idx += 1







"""simple docstring"""
# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


__SCREAMING_SNAKE_CASE							:    Union[str, Any]		=    Path(__file__).resolve().parents[3] / 'src'
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

__SCREAMING_SNAKE_CASE							:    Dict		=    {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'}

__SCREAMING_SNAKE_CASE							:    Dict		=    'zero2'
__SCREAMING_SNAKE_CASE							:    List[Any]		=    'zero3'
__SCREAMING_SNAKE_CASE							:    int		=    [ZEROa, ZEROa]







def 						_a				(      _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE				, _SCREAMING_SNAKE_CASE				)    ->				Union[str, Any]:
							# customize the test name generator function as we want both params to appear in the sub-test
							# name, as by default it shows only the first param
							snake_case_           =		parameterized.to_safe_name("""_""".join(str(_SCREAMING_SNAKE_CASE				) for x in param.args				)				)
							return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
__SCREAMING_SNAKE_CASE							:    Dict		=    list(itertools.product(stages, models.keys()))





@slow
@require_deepspeed
@require_torch_gpu
class      __A     (snake_case__):





							'''simple docstring'''

							@parameterized.expand(UpperCAmelCase_		,       name_func=UpperCAmelCase_       )
							def 		lowerCAmelCase       (				self							:      Union[str, Any]		,       UpperCAmelCase_							:      Dict		,       UpperCAmelCase_							:      Union[str, Any]       )					->Any:



														"""simple docstring"""



														self.run_and_check(
														    stage=UpperCAmelCase_		,       model=UpperCAmelCase_		,       distributed=UpperCAmelCase_		,       fpaa=UpperCAmelCase_		,       )



							@require_torch_multi_gpu
							@parameterized.expand(UpperCAmelCase_		,       name_func=UpperCAmelCase_       )
							def 		lowerCAmelCase       (				self							:      Optional[int]		,       UpperCAmelCase_							:      List[Any]		,       UpperCAmelCase_							:      Optional[Any]       )					->Optional[Any]:



														"""simple docstring"""



														self.run_and_check(
														    stage=UpperCAmelCase_		,       model=UpperCAmelCase_		,       distributed=UpperCAmelCase_		,       fpaa=UpperCAmelCase_		,       )



							@parameterized.expand(UpperCAmelCase_		,       name_func=UpperCAmelCase_       )
							def 		lowerCAmelCase       (				self							:      Tuple		,       UpperCAmelCase_							:      Dict		,       UpperCAmelCase_							:      Optional[int]       )					->List[str]:



														"""simple docstring"""



														self.run_and_check(
														    stage=UpperCAmelCase_		,       model=UpperCAmelCase_		,       distributed=UpperCAmelCase_		,       fpaa=UpperCAmelCase_		,       )



							@require_torch_multi_gpu
							@parameterized.expand(UpperCAmelCase_		,       name_func=UpperCAmelCase_       )
							def 		lowerCAmelCase       (				self							:      Dict		,       UpperCAmelCase_							:      str		,       UpperCAmelCase_							:      List[Any]       )					->Optional[int]:



														"""simple docstring"""



														self.run_and_check(
														    stage=UpperCAmelCase_		,       model=UpperCAmelCase_		,       distributed=UpperCAmelCase_		,       fpaa=UpperCAmelCase_		,       )



							def 		lowerCAmelCase       (				self							:      Optional[int]		,       UpperCAmelCase_							:      Union[str, Any]       )					->Optional[int]:



														"""simple docstring"""



														pass



							def 		lowerCAmelCase       (				self							:      Any		,       UpperCAmelCase_							:      str		,       UpperCAmelCase_							:      str		,       UpperCAmelCase_							:      int = 10		,       UpperCAmelCase_							:      bool = True		,       UpperCAmelCase_							:      bool = True		,       UpperCAmelCase_							:      bool = True		,       )					->List[str]:



														"""simple docstring"""



														snake_case_           =		models[model]

														snake_case_           =		self.run_trainer(
														    stage=UpperCAmelCase_		,       model_name=UpperCAmelCase_		,       eval_steps=UpperCAmelCase_		,       num_train_epochs=1		,       distributed=UpperCAmelCase_		,       fpaa=UpperCAmelCase_		,       )

														self.do_checks(UpperCAmelCase_       )

														return output_dir



							def 		lowerCAmelCase       (				self							:      Union[str, Any]		,       UpperCAmelCase_							:      str		,       UpperCAmelCase_							:      str		,       UpperCAmelCase_							:      int = 10		,       UpperCAmelCase_							:      int = 1		,       UpperCAmelCase_							:      bool = True		,       UpperCAmelCase_							:      bool = True		,       )					->List[str]:



														"""simple docstring"""



														snake_case_           =		self.get_auto_remove_tmp_dir("""./xxx"""		,       after=UpperCAmelCase_       )
														snake_case_           =		F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(UpperCAmelCase_       )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

														if fpaa:
																					args.extend(["""--fp16"""]       )

														# currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
														# hence the separate config files
														snake_case_           =		F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
														snake_case_           =		[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
														snake_case_           =		self.get_launcher(UpperCAmelCase_       )

														snake_case_           =		launcher + script + args + ds_args
														# keep for quick debug
														# print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
														execute_subprocess_async(UpperCAmelCase_		,       env=self.get_env()       )

														return output_dir



							def 		lowerCAmelCase       (				self							:      Union[str, Any]		,       UpperCAmelCase_							:      Any=False       )					->Tuple:



														"""simple docstring"""



														snake_case_           =		min(2		,       get_gpu_count()       ) if distributed else 1
														return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()



