






import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('3.8'):
					import importlib_metadata
else:
					import importlib.metadata as importlib_metadata







def      snake_case		(							UpperCAmelCase	:       Dict,						UpperCAmelCase	:       Tuple=False   ):


				try:
								A	 =      os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								A	 =      default
				else:
								# KEY is set, convert it to True or False.
								try:
												A	 =      strtobool(lowerCAmelCase_   )
								except ValueError:
												# More values are supported, but let's keep the message simple.
												raise ValueError(f'If set, {key} must be yes or no.'   )
				return _value


lowerCAmelCase_           = parse_flag_from_env('RUN_SLOW', default=False)
lowerCAmelCase_           = parse_flag_from_env('RUN_REMOTE', default=False)
lowerCAmelCase_           = parse_flag_from_env('RUN_LOCAL', default=True)
lowerCAmelCase_           = parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
lowerCAmelCase_           = pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
lowerCAmelCase_           = pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
lowerCAmelCase_           = pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
lowerCAmelCase_           = pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'),
    reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ',
)

# Beam
lowerCAmelCase_           = pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'),
    reason='test requires apache-beam and a compatible dill version',
)

# Dill-cloudpickle compatibility
lowerCAmelCase_           = pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
lowerCAmelCase_           = pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)







def      snake_case		(							UpperCAmelCase	:       str   ):


				try:
								import faiss  # noqa
				except ImportError:
								A	 =      unittest.skip('test requires faiss'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       int   ):


				try:
								import regex  # noqa
				except ImportError:
								A	 =      unittest.skip('test requires regex'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Any   ):


				try:
								import elasticsearch  # noqa
				except ImportError:
								A	 =      unittest.skip('test requires elasticsearch'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Tuple   ):


				try:
								import sqlalchemy  # noqa
				except ImportError:
								A	 =      unittest.skip('test requires sqlalchemy'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Optional[int]   ):


				if not config.TORCH_AVAILABLE:
								A	 =      unittest.skip('test requires PyTorch'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Dict   ):


				if not config.TF_AVAILABLE:
								A	 =      unittest.skip('test requires TensorFlow'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       List[str]   ):


				if not config.JAX_AVAILABLE:
								A	 =      unittest.skip('test requires JAX'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       str   ):


				if not config.PIL_AVAILABLE:
								A	 =      unittest.skip('test requires Pillow'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Union[str, Any]   ):


				try:
								import transformers  # noqa F401
				except ImportError:
								return unittest.skip('test requires transformers'   )(lowerCAmelCase_   )
				else:
								return test_case







def      snake_case		(							UpperCAmelCase	:       List[str]   ):


				try:
								import tiktoken  # noqa F401
				except ImportError:
								return unittest.skip('test requires tiktoken'   )(lowerCAmelCase_   )
				else:
								return test_case







def      snake_case		(							UpperCAmelCase	:       Optional[Any]   ):


				try:
								import spacy  # noqa F401
				except ImportError:
								return unittest.skip('test requires spacy'   )(lowerCAmelCase_   )
				else:
								return test_case







def      snake_case		(							UpperCAmelCase	:       Dict   ):


				def _require_spacy_model(UpperCAmelCase	:       Tuple   ):
								try:
												import spacy  # noqa F401

												spacy.load(lowerCAmelCase_   )
								except ImportError:
												return unittest.skip('test requires spacy'   )(lowerCAmelCase_   )
								except OSError:
												return unittest.skip('test requires spacy model \'{}\''.format(lowerCAmelCase_   )   )(lowerCAmelCase_   )
								else:
												return test_case

				return _require_spacy_model







def      snake_case		(							UpperCAmelCase	:       Optional[int]   ):


				try:
								import pyspark  # noqa F401
				except ImportError:
								return unittest.skip('test requires pyspark'   )(lowerCAmelCase_   )
				else:
								return test_case







def      snake_case		(							UpperCAmelCase	:       Dict   ):


				try:
								import joblibspark  # noqa F401
				except ImportError:
								return unittest.skip('test requires joblibspark'   )(lowerCAmelCase_   )
				else:
								return test_case







def      snake_case		(							UpperCAmelCase	:       int   ):


				if not _run_slow_tests or _run_slow_tests == 0:
								A	 =      unittest.skip('test is slow'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       str   ):


				if not _run_local_tests or _run_local_tests == 0:
								A	 =      unittest.skip('test is local'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Optional[Any]   ):


				if not _run_packaged_tests or _run_packaged_tests == 0:
								A	 =      unittest.skip('test is packaged'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							UpperCAmelCase	:       Optional[int]   ):


				if not _run_remote_tests or _run_remote_tests == 0:
								A	 =      unittest.skip('test requires remote'   )(lowerCAmelCase_   )
				return test_case







def      snake_case		(							*UpperCAmelCase	:       List[Any]   ):


				def decorate(cls	:       List[str]   ):
								for name, fn in cls.__dict__.items():
												if callable(lowerCAmelCase_   ) and name.startswith('test'   ):
																for decorator in decorators:
																				A	 =      decorator(lowerCAmelCase_   )
																setattr(cls,						lowerCAmelCase_,						lowerCAmelCase_   )
								return cls

				return decorate
class      UpperCamelCase (				__lowerCamelCase ):







		"""simple docstring"""



		pass


class      UpperCamelCase (				__lowerCamelCase ):







		"""simple docstring"""



		snake_case    =   0
		snake_case    =   1
		snake_case    =   2







@contextmanager
def      snake_case		(							UpperCAmelCase	:       Optional[int]=OfflineSimulationMode.CONNECTION_FAILS,						UpperCAmelCase	:       List[str]=1E-1_6   ):
				A	 =      requests.Session().request

				def timeout_request(UpperCAmelCase	:       Dict,						UpperCAmelCase	:       Optional[Any],						UpperCAmelCase	:       Tuple,						**UpperCAmelCase	:       Optional[Any]   ):
								# Change the url to an invalid url so that the connection hangs
								A	 =      "https://10.255.255.1"
								if kwargs.get('timeout'   ) is None:
												raise RequestWouldHangIndefinitelyError(
												    f'Tried a call to {url} in offline mode with no timeout set. Please set a timeout.'   )
								A	 =      timeout
								try:
												return online_request(lowerCAmelCase_,						lowerCAmelCase_,						**lowerCAmelCase_   )
								except Exception as e:
												# The following changes in the error are just here to make the offline timeout error prettier
												A	 =      url
												A	 =      e.args[0]
												A	 =      (max_retry_error.args[0].replace('10.255.255.1',						f'OfflineMock[{url}]'   ),)
												A	 =      (max_retry_error,)
												raise

				def raise_connection_error(UpperCAmelCase	:       Optional[int],						UpperCAmelCase	:       Dict,						**UpperCAmelCase	:       Optional[int]   ):
								raise requests.ConnectionError('Offline mode is enabled.',						request=lowerCAmelCase_   )

				if mode is OfflineSimulationMode.CONNECTION_FAILS:
								with patch('requests.Session.send',						lowerCAmelCase_   ):
												yield
				elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
								# inspired from https://stackoverflow.com/a/904609
								with patch('requests.Session.request',						lowerCAmelCase_   ):
												yield
				elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
								with patch('datasets.config.HF_DATASETS_OFFLINE',						lowerCAmelCase_   ):
												yield
				else:
								raise ValueError('Please use a value from the OfflineSimulationMode enum.'   )







@contextmanager
def      snake_case		(							*UpperCAmelCase	:       Optional[int],						**UpperCAmelCase	:       Tuple   ):
				A	 =      str(Path().resolve()   )
				with tempfile.TemporaryDirectory(*lowerCAmelCase_,						**lowerCAmelCase_   ) as tmp_dir:
								try:
												os.chdir(lowerCAmelCase_   )
												yield
								finally:
												os.chdir(lowerCAmelCase_   )







@contextmanager
def      snake_case		(							):
				import gc

				gc.collect()
				A	 =      pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."







@contextmanager
def      snake_case		(							):
				import gc

				gc.collect()
				A	 =      pa.total_allocated_bytes()
				yield
				assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."







def      snake_case		(							UpperCAmelCase	:       List[str],						UpperCAmelCase	:       Any   ):
				return deepcopy(lowerCAmelCase_   ).integers(0,						1_00,						10   ).tolist() == deepcopy(lowerCAmelCase_   ).integers(0,						1_00,						10   ).tolist()







def      snake_case		(							UpperCAmelCase	:       str   ):
				import decorator
				from requests.exceptions import HTTPError

				def _wrapper(UpperCAmelCase	:       int,						*UpperCAmelCase	:       Dict,						**UpperCAmelCase	:       List[str]   ):
								try:
												return func(*lowerCAmelCase_,						**lowerCAmelCase_   )
								except HTTPError as err:
												if str(lowerCAmelCase_   ).startswith('500'   ) or str(lowerCAmelCase_   ).startswith('502'   ):
																pytest.xfail(str(lowerCAmelCase_   )   )
												raise err

				return decorator.decorator(_wrapper,						lowerCAmelCase_   )
class      UpperCamelCase :







		"""simple docstring"""



		def __init__(  self		:       Tuple						,_SCREAMING_SNAKE_CASE		:       List[str]						,_SCREAMING_SNAKE_CASE		:       List[str]						,_SCREAMING_SNAKE_CASE		:       Any		)    ->   Any:


						'''simple docstring'''
						A	 =      returncode
						A	 =      stdout
						A	 =      stderr







async def      snake_case		(							UpperCAmelCase	:       Optional[int],						UpperCAmelCase	:       Tuple   ):


				while True:
								A	 =      await stream.readline()
								if line:
												callback(lowerCAmelCase_   )
								else:
												break







async def      snake_case		(							UpperCAmelCase	:       List[Any],						UpperCAmelCase	:       Tuple=None,						UpperCAmelCase	:       int=None,						UpperCAmelCase	:       Tuple=None,						UpperCAmelCase	:       List[str]=False,						UpperCAmelCase	:       Optional[Any]=False   ):


				if echo:
								print('\nRunning: ',						' '.join(lowerCAmelCase_   )   )

				A	 =      await asyncio.create_subprocess_exec(
				    cmd[0],						*cmd[1:],						stdin=lowerCAmelCase_,						stdout=asyncio.subprocess.PIPE,						stderr=asyncio.subprocess.PIPE,						env=lowerCAmelCase_,						)

				# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
				# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
				#
				# If it starts hanging, will need to switch to the following code. The problem is that no data
				# will be seen until it's done and if it hangs for example there will be no debug info.
				# out, err = await p.communicate()
				# return _RunOutput(p.returncode, out, err)

				A	 =      []
				A	 =      []

				def tee(UpperCAmelCase	:       int,						UpperCAmelCase	:       Any,						UpperCAmelCase	:       int,						UpperCAmelCase	:       str=""   ):
								A	 =      line.decode('utf-8'   ).rstrip()
								sink.append(lowerCAmelCase_   )
								if not quiet:
												print(lowerCAmelCase_,						lowerCAmelCase_,						file=lowerCAmelCase_   )

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        _read_stream(p.stdout,						lambda UpperCAmelCase   : tee(lowerCAmelCase_,						lowerCAmelCase_,						sys.stdout,						label='stdout:'   )   ),
				        _read_stream(p.stderr,						lambda UpperCAmelCase   : tee(lowerCAmelCase_,						lowerCAmelCase_,						sys.stderr,						label='stderr:'   )   ),
				    ],						timeout=lowerCAmelCase_,						)
				return _RunOutput(await p.wait(),						lowerCAmelCase_,						lowerCAmelCase_   )







def      snake_case		(							UpperCAmelCase	:       List[str],						UpperCAmelCase	:       int=None,						UpperCAmelCase	:       int=None,						UpperCAmelCase	:       List[Any]=1_80,						UpperCAmelCase	:       List[Any]=False,						UpperCAmelCase	:       List[str]=True   ):
				A	 =      asyncio.get_event_loop()
				A	 =      loop.run_until_complete(
				    _stream_subprocess(lowerCAmelCase_,						env=lowerCAmelCase_,						stdin=lowerCAmelCase_,						timeout=lowerCAmelCase_,						quiet=lowerCAmelCase_,						echo=lowerCAmelCase_   )   )

				A	 =      " ".join(lowerCAmelCase_   )
				if result.returncode > 0:
								A	 =      "\n".join(result.stderr   )
								raise RuntimeError(
								    f'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
								    f'The combined stderr from workers follows:\n{stderr}'   )

				# check that the subprocess actually did run and produced some output, should the test rely on
				# the remote side to do the testing
				if not result.stdout and not result.stderr:
								raise RuntimeError(f'\'{cmd_str}\' produced no output.'   )

				return result







def      snake_case		(							):
				A	 =      os.environ.get('PYTEST_XDIST_WORKER',						'gw0'   )
				A	 =      re.sub(r'^gw',						'',						lowerCAmelCase_,						0,						re.M   )
				return int(lowerCAmelCase_   )







def      snake_case		(							):
				A	 =      2_95_00
				A	 =      pytest_xdist_worker_id()
				return port + uniq_delta













import argparse

import torch
from torch import nn

from transformers import SpeechaTextConfig, SpeechaTextForConditionalGeneration







def      snake_case		(							UpperCAmelCase	:       List[Any]   ):
				A	 =      [
				    'encoder.version',
				    'decoder.version',
				    'model.encoder.version',
				    'model.decoder.version',
				    'decoder.output_projection.weight',
				    '_float_tensor',
				    'encoder.embed_positions._float_tensor',
				    'decoder.embed_positions._float_tensor',
				]
				for k in ignore_keys:
								state_dict.pop(UpperCAmelCase,						UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Union[str, Any]   ):
				A	 =      list(s_dict.keys()   )
				for key in keys:
								if "transformer_layers" in key:
												A	 =      s_dict.pop(UpperCAmelCase   )
								elif "subsample" in key:
												A	 =      s_dict.pop(UpperCAmelCase   )







def      snake_case		(							UpperCAmelCase	:       Union[str, Any]   ):
				A ,		A	 =      emb.weight.shape
				A	 =      nn.Linear(UpperCAmelCase,						UpperCAmelCase,						bias=UpperCAmelCase   )
				A	 =      emb.weight.data
				return lin_layer







def      snake_case		(							UpperCAmelCase	:       str,						UpperCAmelCase	:       str   ):
				A	 =      torch.load(UpperCAmelCase,						map_location='cpu'   )
				A	 =      mam_aaa['args']
				A	 =      mam_aaa['model']
				A	 =      state_dict['decoder.output_projection.weight']

				remove_ignore_keys_(UpperCAmelCase   )
				rename_keys(UpperCAmelCase   )

				A	 =      state_dict['decoder.embed_tokens.weight'].shape[0]

				A	 =      args.share_decoder_input_output_embed

				A	 =      [int(UpperCAmelCase   ) for i in args.conv_kernel_sizes.split(','   )]
				A	 =      SpeechaTextConfig(
				    vocab_size=UpperCAmelCase,						max_source_positions=args.max_source_positions,						max_target_positions=args.max_target_positions,						encoder_layers=args.encoder_layers,						decoder_layers=args.decoder_layers,						encoder_attention_heads=args.encoder_attention_heads,						decoder_attention_heads=args.decoder_attention_heads,						encoder_ffn_dim=args.encoder_ffn_embed_dim,						decoder_ffn_dim=args.decoder_ffn_embed_dim,						d_model=args.encoder_embed_dim,						dropout=args.dropout,						attention_dropout=args.attention_dropout,						activation_dropout=args.activation_dropout,						activation_function='relu',						num_conv_layers=len(UpperCAmelCase   ),						conv_channels=args.conv_channels,						conv_kernel_sizes=UpperCAmelCase,						input_feat_per_channel=args.input_feat_per_channel,						input_channels=args.input_channels,						tie_word_embeddings=UpperCAmelCase,						num_beams=5,						max_length=2_00,						use_cache=UpperCAmelCase,						decoder_start_token_id=2,						early_stopping=UpperCAmelCase,						)

				A	 =      SpeechaTextForConditionalGeneration(UpperCAmelCase   )
				A ,		A	 =      model.model.load_state_dict(UpperCAmelCase,						strict=UpperCAmelCase   )
				if len(UpperCAmelCase   ) > 0 and not set(UpperCAmelCase   ) <= {
				    "encoder.embed_positions.weights",
				    "decoder.embed_positions.weights",
				}:
								raise ValueError(
								    'Only `encoder.embed_positions.weights` and `decoder.embed_positions.weights`  are allowed to be missing,'
								    f' but all the following weights are missing {missing}'   )

				if tie_embeds:
								A	 =      make_linear_from_emb(model.model.decoder.embed_tokens   )
				else:
								A	 =      lm_head_weights

				model.save_pretrained(UpperCAmelCase   )


if __name__ == "__main__":
					lowerCAmelCase_           = argparse.ArgumentParser()
					# Required parameters
					parser.add_argument('--fairseq_path', type=str, help='Path to the fairseq model (.pt) file.')
					parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
					lowerCAmelCase_           = parser.parse_args()
					convert_fairseq_sat_checkpoint_to_tfms(args.fairseq_path, args.pytorch_dump_folder_path)





