




import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
					from transformers import WhisperFeatureExtractor

if is_torch_available():
					import torch

UpperCamelCase__    			=			random.Random()







def 	_a      (						SCREAMING_SNAKE_CASE_							:				Optional[Any]      ,      SCREAMING_SNAKE_CASE_							:				List[str]=1.0      ,      SCREAMING_SNAKE_CASE_							:				Dict=None      ,      SCREAMING_SNAKE_CASE_							:				Dict=None     ):






					if rng is None:
										__lowerCAmelCase				   =       global_rng

					__lowerCAmelCase				   =       []
					for batch_idx in range(shape[0]     ):
										values.append([]     )
										for _ in range(shape[1]     ):
															values[-1].append(rng.random() * scale     )

					return values
@require_torch
@require_torchaudio
class 			a__    (					unittest.TestCase      ):






						def __init__(   self		,			_A		,			_A=7		,			_A=4_0_0		,			_A=2_0_0_0		,			_A=1_0		,			_A=1_6_0		,			_A=8		,			_A=0.0		,			_A=4_0_0_0		,			_A=False		,			_A=True		,			):




											"""simple docstring"""



											__lowerCAmelCase				   =       parent
											__lowerCAmelCase				   =       batch_size
											__lowerCAmelCase				   =       min_seq_length
											__lowerCAmelCase				   =       max_seq_length
											__lowerCAmelCase				   =       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
											__lowerCAmelCase				   =       padding_value
											__lowerCAmelCase				   =       sampling_rate
											__lowerCAmelCase				   =       return_attention_mask
											__lowerCAmelCase				   =       do_normalize
											__lowerCAmelCase				   =       feature_size
											__lowerCAmelCase				   =       chunk_length
											__lowerCAmelCase				   =       hop_length






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											return {
											    "feature_size": self.feature_size,
											    "hop_length": self.hop_length,
											    "chunk_length": self.chunk_length,
											    "padding_value": self.padding_value,
											    "sampling_rate": self.sampling_rate,
											    "return_attention_mask": self.return_attention_mask,
											    "do_normalize": self.do_normalize,
											}






						def 				__SCREAMING_SNAKE_CASE(   self		,			_A=False		,			_A=False			):




											"""simple docstring"""



											def _flatten(_A			):
																return list(itertools.chain(*lowerCAmelCase__			)			)

											if equal_length:
																__lowerCAmelCase				   =       [floats_list((self.max_seq_length, self.feature_size)			) for _ in range(self.batch_size			)]
											else:
																# make sure that inputs increase in size
																__lowerCAmelCase				   =       [
																    floats_list((x, self.feature_size)			)
																    for x in range(self.min_seq_length		,			self.max_seq_length		,			self.seq_length_diff			)
																]
											if numpify:
																__lowerCAmelCase				   =       [np.asarray(lowerCAmelCase__			) for x in speech_inputs]
											return speech_inputs






@require_torch
@require_torchaudio
class 			a__    (					a__ ,				unittest.TestCase      ):
						_a							:    Tuple					=    WhisperFeatureExtractor if is_speech_available() else None






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       WhisperFeatureExtractionTester(self			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       self.feature_extraction_class(**self.feat_extract_dict			)

											with tempfile.TemporaryDirectory() as tmpdirname:
																__lowerCAmelCase				   =       feat_extract_first.save_pretrained(lowerCAmelCase__			)[0]
																check_json_file_has_correct_format(lowerCAmelCase__			)
																__lowerCAmelCase				   =       self.feature_extraction_class.from_pretrained(lowerCAmelCase__			)

											__lowerCAmelCase				   =       feat_extract_first.to_dict()
											__lowerCAmelCase				   =       feat_extract_second.to_dict()
											__lowerCAmelCase				   =       feat_extract_first.mel_filters
											__lowerCAmelCase				   =       feat_extract_second.mel_filters
											self.assertTrue(np.allclose(lowerCAmelCase__		,			lowerCAmelCase__			)			)
											self.assertEqual(lowerCAmelCase__		,			lowerCAmelCase__			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       self.feature_extraction_class(**self.feat_extract_dict			)

											with tempfile.TemporaryDirectory() as tmpdirname:
																__lowerCAmelCase				   =       os.path.join(lowerCAmelCase__		,			"feat_extract.json"			)
																feat_extract_first.to_json_file(lowerCAmelCase__			)
																__lowerCAmelCase				   =       self.feature_extraction_class.from_json_file(lowerCAmelCase__			)

											__lowerCAmelCase				   =       feat_extract_first.to_dict()
											__lowerCAmelCase				   =       feat_extract_second.to_dict()
											__lowerCAmelCase				   =       feat_extract_first.mel_filters
											__lowerCAmelCase				   =       feat_extract_second.mel_filters
											self.assertTrue(np.allclose(lowerCAmelCase__		,			lowerCAmelCase__			)			)
											self.assertEqual(lowerCAmelCase__		,			lowerCAmelCase__			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()			)
											# create three inputs of length 800, 1000, and 1200
											__lowerCAmelCase				   =       [floats_list((1, x)			)[0] for x in range(8_0_0		,			1_4_0_0		,			2_0_0			)]
											__lowerCAmelCase				   =       [np.asarray(lowerCAmelCase__			) for speech_input in speech_inputs]

											# Test feature size
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			padding="max_length"		,			return_tensors="np"			).input_features
											self.assertTrue(input_features.ndim == 3			)
											self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames			)
											self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size			)

											# Test not batched input
											__lowerCAmelCase				   =       feature_extractor(speech_inputs[0]		,			return_tensors="np"			).input_features
											__lowerCAmelCase				   =       feature_extractor(np_speech_inputs[0]		,			return_tensors="np"			).input_features
											self.assertTrue(np.allclose(lowerCAmelCase__		,			lowerCAmelCase__		,			atol=1E-3			)			)

											# Test batched
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="np"			).input_features
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="np"			).input_features
											for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__		,			lowerCAmelCase__			):
																self.assertTrue(np.allclose(lowerCAmelCase__		,			lowerCAmelCase__		,			atol=1E-3			)			)

											# Test 2-D numpy arrays are batched.
											__lowerCAmelCase				   =       [floats_list((1, x)			)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
											__lowerCAmelCase				   =       np.asarray(lowerCAmelCase__			)
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="np"			).input_features
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="np"			).input_features
											for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__		,			lowerCAmelCase__			):
																self.assertTrue(np.allclose(lowerCAmelCase__		,			lowerCAmelCase__		,			atol=1E-3			)			)

											# Test truncation required
											__lowerCAmelCase				   =       [floats_list((1, x)			)[0] for x in range(2_0_0		,			(feature_extractor.n_samples + 5_0_0)		,			2_0_0			)]
											__lowerCAmelCase				   =       [np.asarray(lowerCAmelCase__			) for speech_input in speech_inputs]

											__lowerCAmelCase				   =       [x[: feature_extractor.n_samples] for x in speech_inputs]
											__lowerCAmelCase				   =       [np.asarray(lowerCAmelCase__			) for speech_input in speech_inputs_truncated]

											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="np"			).input_features
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="np"			).input_features
											for enc_seq_a, enc_seq_a in zip(lowerCAmelCase__		,			lowerCAmelCase__			):
																self.assertTrue(np.allclose(lowerCAmelCase__		,			lowerCAmelCase__		,			atol=1E-3			)			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											import torch

											__lowerCAmelCase				   =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()			)
											__lowerCAmelCase				   =       np.random.rand(1_0_0		,			3_2			).astype(np.floataa			)
											__lowerCAmelCase				   =       np_speech_inputs.tolist()

											for inputs in [py_speech_inputs, np_speech_inputs]:
																__lowerCAmelCase				   =       feature_extractor.pad([{"input_features": inputs}]		,			return_tensors="np"			)
																self.assertTrue(np_processed.input_features.dtype == np.floataa			)
																__lowerCAmelCase				   =       feature_extractor.pad([{"input_features": inputs}]		,			return_tensors="pt"			)
																self.assertTrue(pt_processed.input_features.dtype == torch.floataa			)






						def 				__SCREAMING_SNAKE_CASE(   self		,			_A			):




											"""simple docstring"""



											__lowerCAmelCase				   =       load_dataset("hf-internal-testing/librispeech_asr_dummy"		,			"clean"		,			split="validation"			)
											# automatic decoding with librispeech
											__lowerCAmelCase				   =       ds.sort("id"			).select(range(lowerCAmelCase__			)			)[:num_samples]["audio"]

											return [x["array"] for x in speech_samples]






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       torch.tensor(
											    [
											        0.11_93, -0.09_46, -0.10_98, -0.01_96, 0.02_25, -0.06_90, -0.17_36, 0.09_51,
											        0.09_71, -0.08_17, -0.07_02, 0.01_62, 0.02_60, 0.00_17, -0.01_92, -0.16_78,
											        0.07_09, -0.18_67, -0.06_55, -0.02_74, -0.02_34, -0.18_84, -0.05_16, -0.05_54,
											        -0.02_74, -0.14_25, -0.14_23, 0.08_37, 0.03_77, -0.08_54
											    ]			)
											# fmt: on

											__lowerCAmelCase				   =       self._load_datasamples(1			)
											__lowerCAmelCase				   =       WhisperFeatureExtractor()
											__lowerCAmelCase				   =       feature_extractor(lowerCAmelCase__		,			return_tensors="pt"			).input_features
											self.assertEqual(input_features.shape		,			(1, 8_0, 3_0_0_0)			)
											self.assertTrue(torch.allclose(input_features[0, 0, :3_0]		,			lowerCAmelCase__		,			atol=1E-4			)			)






						def 				__SCREAMING_SNAKE_CASE(   self			):




											"""simple docstring"""



											__lowerCAmelCase				   =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()			)
											__lowerCAmelCase				   =       self._load_datasamples(1			)[0]
											__lowerCAmelCase				   =       ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
											__lowerCAmelCase				   =       feat_extract.zero_mean_unit_var_norm([audio]		,			attention_mask=lowerCAmelCase__			)[0]

											self.assertTrue(np.all(np.mean(lowerCAmelCase__			) < 1E-3			)			)
											self.assertTrue(np.all(np.abs(np.var(lowerCAmelCase__			) - 1			) < 1E-3			)			)











"""simple docstring"""




import os
import re
import shutil
from argparse import ArgumentParser, Namespace

from datasets.commands import BaseDatasetsCLICommand
from datasets.utils.logging import get_logger


a						: int     	=			'''<<<<<<< This should probably be modified because it mentions: '''

a						: Tuple     	=			'''=======
>>>>>>>
'''

a						: List[Any]     	=			[
    '''TextEncoderConfig''',
    '''ByteTextEncoder''',
    '''SubwordTextEncoder''',
    '''encoder_config''',
    '''maybe_build_from_corpus''',
    '''manual_dir''',
]

a						: Union[str, Any]     	=			[
    # (pattern, replacement)
    # Order is important here for some replacements
    (R'''tfds\.core''', R'''datasets'''),
    (R'''tf\.io\.gfile\.GFile''', R'''open'''),
    (R'''tf\.([\w\d]+)''', R'''datasets.Value(\'\1\')'''),
    (R'''tfds\.features\.Text\(\)''', R'''datasets.Value(\'string\')'''),
    (R'''tfds\.features\.Text\(''', R'''datasets.Value(\'string\'),'''),
    (R'''features\s*=\s*tfds.features.FeaturesDict\(''', R'''features=datasets.Features('''),
    (R'''tfds\.features\.FeaturesDict\(''', R'''dict('''),
    (R'''The TensorFlow Datasets Authors''', R'''The TensorFlow Datasets Authors and the HuggingFace Datasets Authors'''),
    (R'''tfds\.''', R'''datasets.'''),
    (R'''dl_manager\.manual_dir''', R'''self.config.data_dir'''),
    (R'''self\.builder_config''', R'''self.config'''),
]






def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Namespace					) ->Any:






	'''simple docstring'''






	return ConvertCommand(args.tfds_path    ,       args.datasets_directory					)







class        __UpperCamelCase				(						a__						):






							@staticmethod
							def     __a   (   lowerCAmelCase__      )	-> int:
								a      :		Any	=				parser.add_parser(
								    "convert"      ,					help="Convert a TensorFlow Datasets dataset to a HuggingFace Datasets dataset."      ,					)
								train_parser.add_argument(
								    "--tfds_path"      ,					type=lowerCAmelCase__      ,					required=lowerCAmelCase__      ,					help="Path to a TensorFlow Datasets folder to convert or a single tfds file to convert."      ,					)
								train_parser.add_argument(
								    "--datasets_directory"      ,					type=lowerCAmelCase__      ,					required=lowerCAmelCase__      ,					help="Path to the HuggingFace Datasets folder."      )
								train_parser.set_defaults(func=lowerCAmelCase__      )






							def __init__(   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					*lowerCAmelCase__      )	-> Tuple:
								a      :		List[str]	=				get_logger("datasets-cli/converting"      )

								a      :		Optional[int]	=				tfds_path
								a      :		str	=				datasets_directory






							def     __a   (   self      )	-> str:
								if os.path.isdir(self._tfds_path      ):
									a      :		int	=				os.path.abspath(self._tfds_path      )
								elif os.path.isfile(self._tfds_path      ):
									a      :		Optional[Any]	=				os.path.dirname(self._tfds_path      )
								else:
									raise ValueError("--tfds_path is neither a directory nor a file. Please check path."      )

								a      :		str	=				os.path.abspath(self._datasets_directory      )

								self._logger.info(f"""Converting datasets from {abs_tfds_path} to {abs_datasets_path}"""      )

								a      :		str	=				[]
								a      :		Union[str, Any]	=				[]
								a      :		str	=				{}

								if os.path.isdir(self._tfds_path      ):
									a      :		Dict	=				os.listdir(lowerCAmelCase__      )
								else:
									a      :		Dict	=				[os.path.basename(self._tfds_path      )]

								for f_name in file_names:
									self._logger.info(f"""Looking at file {f_name}"""      )
									a      :		Any	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )
									a      :		Dict	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )

									if not os.path.isfile(lowerCAmelCase__      ) or "__init__" in f_name or "_test" in f_name or ".py" not in f_name:
										self._logger.info("Skipping file"      )
										continue

									with open(lowerCAmelCase__      ,					encoding="utf-8"      ) as f:
										a      :		Any	=				f.readlines()

									a      :		Tuple	=				[]
									a      :		Any	=				False
									a      :		Dict	=				False
									a      :		Dict	=				[]
									for line in lines:
										a      :		Tuple	=				line

										# Convert imports
										if "import tensorflow.compat.v2 as tf" in out_line:
											continue
										elif "@tfds.core" in out_line:
											continue
										elif "builder=self" in out_line:
											continue
										elif "import tensorflow_datasets.public_api as tfds" in out_line:
											a      :		Optional[int]	=				"import datasets\n"
										elif "import tensorflow" in out_line:
											# order is important here
											a      :		Optional[Any]	=				""
											continue
										elif "from absl import logging" in out_line:
											a      :		Any	=				"from datasets import logging\n"
										elif "getLogger" in out_line:
											a      :		int	=				out_line.replace("getLogger"      ,					"get_logger"      )
										elif any(expression in out_line for expression in TO_HIGHLIGHT      ):
											a      :		Optional[Any]	=				True
											a      :		Optional[Any]	=				list(filter(lambda lowerCAmelCase__      : e in out_line      ,					lowerCAmelCase__      )      )
											out_lines.append(HIGHLIGHT_MESSAGE_PRE + str(lowerCAmelCase__      ) + "\n"      )
											out_lines.append(lowerCAmelCase__      )
											out_lines.append(lowerCAmelCase__      )
											continue
										else:
											for pattern, replacement in TO_CONVERT:
												a      :		int	=				re.sub(lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )

                # Take care of saving utilities (to later move them together with main script)
										if "tensorflow_datasets" in out_line:
											a      :		int	=				re.match(R"from\stensorflow_datasets.*import\s([^\.\r\n]+)"      ,					lowerCAmelCase__      )
											tfds_imports.extend(imp.strip() for imp in match.group(1      ).split(","      )      )
											a      :		List[str]	=				"from . import " + match.group(1      )

										# Check we have not forget anything
										if "tf." in out_line or "tfds." in out_line or "tensorflow_datasets" in out_line:
											raise ValueError(f"""Error converting {out_line.strip()}"""      )

										if "GeneratorBasedBuilder" in out_line or "BeamBasedBuilder" in out_line:
											a      :		str	=				True
										out_lines.append(lowerCAmelCase__      )

									if is_builder or "wmt" in f_name:
										# We create a new directory for each dataset
										a      :		Tuple	=				f_name.replace(".py"      ,					""      )
										a      :		Optional[Any]	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )
										a      :		Dict	=				os.path.join(lowerCAmelCase__      ,					lowerCAmelCase__      )
										os.makedirs(lowerCAmelCase__      ,					exist_ok=lowerCAmelCase__      )
										self._logger.info(f"""Adding directory {output_dir}"""      )
										imports_to_builder_map.update({imp: output_dir for imp in tfds_imports}      )
									else:
										# Utilities will be moved at the end
										utils_files.append(lowerCAmelCase__      )

									if needs_manual_update:
										with_manual_update.append(lowerCAmelCase__      )

									with open(lowerCAmelCase__      ,					"w"      ,					encoding="utf-8"      ) as f:
										f.writelines(lowerCAmelCase__      )
									self._logger.info(f"""Converted in {output_file}"""      )

								for utils_file in utils_files:
									try:
										a      :		int	=				os.path.basename(lowerCAmelCase__      )
										a      :		int	=				imports_to_builder_map[f_name.replace(".py"      ,					""      )]
										self._logger.info(f"""Moving {dest_folder} to {utils_file}"""      )
										shutil.copy(lowerCAmelCase__      ,					lowerCAmelCase__      )
									except KeyError:
										self._logger.error(f"""Cannot find destination folder for {utils_file}. Please copy manually."""      )

								if with_manual_update:
									for file_path in with_manual_update:
										self._logger.warning(
										    f"""You need to manually update file {file_path} to remove configurations using 'TextEncoderConfig'."""      )


