

'''simple docstring'''
import argparse
import os
from functools import reduce

import fairseq
import torch
from datasets import load_dataset

from transformers import WavaVecaProcessor, logging
from transformers.models.dataavec.configuration_dataavec_audio import DataaVecAudioConfig

# Copied from https://github.com/pytorch/fairseq/blob/main/examples/data2vec/models/data2vec_audio.py
from transformers.models.dataavec.dataavec_audio import DataaVecAudioModel as Dummy  # noqa: F401
from transformers.models.dataavec.modeling_dataavec_audio import DataaVecAudioForCTC, DataaVecAudioModel


logging.set_verbosity_info()
_lowerCamelCase	 =			logging.get_logger(__name__)

_lowerCamelCase	 =			{
    """post_extract_proj""": """feature_projection.projection""",
    """models.0.layer_norm""": """feature_projection.layer_norm""",
    """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""",
    """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""",
    """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""",
    """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""",
    """self_attn_layer_norm""": """encoder.layers.*.layer_norm""",
    """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""",
    """fc2""": """encoder.layers.*.feed_forward.output_dense""",
    """final_layer_norm""": """encoder.layers.*.final_layer_norm""",
    """encoder.layer_norm""": """encoder.layer_norm""",
    """w2v_model.layer_norm""": """feature_projection.layer_norm""",
    """w2v_encoder.proj""": """lm_head""",
    """mask_emb""": """masked_spec_embed""",
}
_lowerCamelCase	 =			[
    """lm_head""",
]


def       a__    (  _SCREAMING_SNAKE_CASE					:    Optional[Any]     ,							_SCREAMING_SNAKE_CASE					:    List[Any]     ,							_SCREAMING_SNAKE_CASE					:    Union[str, Any]     ,							_SCREAMING_SNAKE_CASE					:    str     ,							_SCREAMING_SNAKE_CASE					:    Dict							)			-> List[str]:


	"""simple docstring"""





	for attribute in key.split("."							):
		UpperCAmelCase_			:	Any      =   getattr(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							)

	if weight_type is not None:
		UpperCAmelCase_			:	Dict      =   getattr(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							).shape
	else:
		UpperCAmelCase_			:	List[str]      =   hf_pointer.shape

	if hf_shape != value.shape:
		raise ValueError(
		    F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
		    F''' {value.shape} for {full_name}'''							)

	if weight_type == "weight":
		UpperCAmelCase_			:	int      =   value
	elif weight_type == "weight_g":
		UpperCAmelCase_			:	Any      =   value
	elif weight_type == "weight_v":
		UpperCAmelCase_			:	List[str]      =   value
	elif weight_type == "bias":
		UpperCAmelCase_			:	str      =   value
	else:
		UpperCAmelCase_			:	Any      =   value

	logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.'''							)


def       a__    (  _SCREAMING_SNAKE_CASE					:    Union[str, Any]     ,							_SCREAMING_SNAKE_CASE					:    str     ,							_SCREAMING_SNAKE_CASE					:    List[Any]							)			-> Optional[int]:


	"""simple docstring"""





	UpperCAmelCase_			:	str      =   []
	UpperCAmelCase_			:	Tuple      =   fairseq_model.state_dict()

	if not is_headless:
		UpperCAmelCase_			:	Optional[Any]      =   hf_model.dataavec_audio.feature_extractor
		UpperCAmelCase_			:	List[Any]      =   hf_model.dataavec_audio.encoder.pos_conv_embed

	else:
		UpperCAmelCase_			:	Any      =   hf_model.feature_extractor
		UpperCAmelCase_			:	Dict      =   hf_model.encoder.pos_conv_embed

	for name, value in fairseq_dict.items():
		UpperCAmelCase_			:	Any      =   False
		if "conv_layers" in name:
			load_conv_layer(
			    _SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							)
			UpperCAmelCase_			:	Any      =   True
		elif "pos_conv" in name:
			load_pos_conv_layer(
			    _SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							)
			UpperCAmelCase_			:	List[str]      =   True
		else:
			for key, mapped_key in MAPPING.items():
				if not is_headless:
					UpperCAmelCase_			:	str      =   "data2vec_audio." + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
				if key in name or key.split("w2v_model."							)[-1] == name.split("."							)[0]:
					UpperCAmelCase_			:	List[str]      =   True
					if "*" in mapped_key:
						UpperCAmelCase_			:	List[Any]      =   name.split(_SCREAMING_SNAKE_CASE							)[0].split("."							)[-2]
						UpperCAmelCase_			:	Optional[Any]      =   mapped_key.replace("*"     ,							_SCREAMING_SNAKE_CASE							)
					if "weight_g" in name:
						UpperCAmelCase_			:	List[str]      =   "weight_g"
					elif "weight_v" in name:
						UpperCAmelCase_			:	Tuple      =   "weight_v"
					elif "bias" in name:
						UpperCAmelCase_			:	Union[str, Any]      =   "bias"
					elif "weight" in name:
						# TODO: don't match quantizer.weight_proj
						UpperCAmelCase_			:	str      =   "weight"
					else:
						UpperCAmelCase_			:	Any      =   None
					set_recursively(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							)
				continue
		if not is_used:
			unused_weights.append(_SCREAMING_SNAKE_CASE							)

	logger.warning(F'''Unused weights: {unused_weights}'''							)


def       a__    (  _SCREAMING_SNAKE_CASE					:    List[str]     ,							_SCREAMING_SNAKE_CASE					:    int							)			-> List[str]:


	"""simple docstring"""





	UpperCAmelCase_			:	List[Any]      =   path.split("."							)
	return reduce(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							)


def       a__    (  _SCREAMING_SNAKE_CASE					:    Any     ,							_SCREAMING_SNAKE_CASE					:    List[Any]     ,							_SCREAMING_SNAKE_CASE					:    Dict     ,							_SCREAMING_SNAKE_CASE					:    List[str]							)			-> Tuple:


	"""simple docstring"""





	UpperCAmelCase_			:	Optional[Any]      =   access_by_string(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							)
	UpperCAmelCase_			:	Union[str, Any]      =   hf_weight.data

	if fsq_value.shape != hf_value.shape:
		raise ValueError(F'''{full_name} has size {fsq_value.shape}, but {hf_value.shape} was found.'''							)
	UpperCAmelCase_			:	Union[str, Any]      =   fsq_value
	logger.info(F'''{full_name} was correctly initialized from {hf_weight_path}.'''							)


def       a__    (  _SCREAMING_SNAKE_CASE					:    List[str]     ,							_SCREAMING_SNAKE_CASE					:    Tuple     ,							_SCREAMING_SNAKE_CASE					:    Dict     ,							_SCREAMING_SNAKE_CASE					:    Tuple							)			-> int:


	"""simple docstring"""





	UpperCAmelCase_			:	Dict      =   full_name.split("conv_layers."							)[-1]
	UpperCAmelCase_			:	Optional[int]      =   name.split("."							)
	UpperCAmelCase_			:	Optional[Any]      =   int(items[0]							)
	UpperCAmelCase_			:	List[str]      =   int(items[1]							)

	UpperCAmelCase_			:	Union[str, Any]      =   name.split("."							)[-1]
	if type_id == 0:
		UpperCAmelCase_			:	Optional[int]      =   "conv"
	elif type_id == 2:
		UpperCAmelCase_			:	Optional[Any]      =   "layer_norm"
	else:
		unused_weights.append(_SCREAMING_SNAKE_CASE							)
		return

	set_weights(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							F'''conv_layers.{layer_id}.{layer_type}.{weight_type}'''							)


def       a__    (  _SCREAMING_SNAKE_CASE					:    List[str]     ,							_SCREAMING_SNAKE_CASE					:    List[Any]     ,							_SCREAMING_SNAKE_CASE					:    int     ,							_SCREAMING_SNAKE_CASE					:    Optional[int]							)			-> List[Any]:


	"""simple docstring"""





	UpperCAmelCase_			:	Optional[Any]      =   full_name.split("pos_conv."							)[-1]
	UpperCAmelCase_			:	Dict      =   name.split("."							)
	UpperCAmelCase_			:	Optional[int]      =   int(items[0]							)
	UpperCAmelCase_			:	List[Any]      =   int(items[1]							)

	UpperCAmelCase_			:	str      =   name.split("."							)[-1]
	if type_id != 0:
		unused_weights.append(_SCREAMING_SNAKE_CASE							)
		return
	else:
		UpperCAmelCase_			:	Optional[Any]      =   "conv"

	set_weights(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							F'''layers.{layer_id}.{layer_type}.{weight_type}'''							)


@torch.no_grad()
def       a__    (  _SCREAMING_SNAKE_CASE					:    Any     ,							_SCREAMING_SNAKE_CASE					:    List[Any]     ,							_SCREAMING_SNAKE_CASE					:    Any=None     ,							_SCREAMING_SNAKE_CASE					:    Union[str, Any]=None     ,							_SCREAMING_SNAKE_CASE					:    List[Any]=True							)			-> List[str]:


	"""simple docstring"""





	if config_path is not None:
		UpperCAmelCase_			:	int      =   DataaVecAudioConfig.from_pretrained(_SCREAMING_SNAKE_CASE							)
	else:
		UpperCAmelCase_			:	List[str]      =   DataaVecAudioConfig()

	if not is_finetuned:
		# Modify final_proj layer name
		UpperCAmelCase_			:	List[str]      =   DataaVecAudioModel(_SCREAMING_SNAKE_CASE							)
		UpperCAmelCase_			:	List[Any]      =   os.path.dirname(_SCREAMING_SNAKE_CASE							)

		UpperCAmelCase_			:	str      =   torch.load(_SCREAMING_SNAKE_CASE							)
		UpperCAmelCase_			:	Union[str, Any]      =   state_dict["model"].pop("final_proj.0.weight"							)
		UpperCAmelCase_			:	Union[str, Any]      =   state_dict["model"].pop("final_proj.0.bias"							)
		UpperCAmelCase_			:	Tuple      =   os.path.join(_SCREAMING_SNAKE_CASE     ,							"converted.pt"							)
		torch.save(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							)
	else:
		UpperCAmelCase_			:	List[Any]      =   DataaVecAudioForCTC(_SCREAMING_SNAKE_CASE							)
		UpperCAmelCase_			:	int      =   checkpoint_path

	def load_dataavec(_SCREAMING_SNAKE_CASE					:    Tuple							):
		UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_			:	List[Any]      =   fairseq.checkpoint_utils.load_model_ensemble_and_task([path]							)
		return model[0].eval()

	UpperCAmelCase_			:	str      =   load_dataavec(_SCREAMING_SNAKE_CASE							)

	recursively_load_weights(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							not is_finetuned							)

	UpperCAmelCase_			:	Tuple      =   WavaVecaProcessor.from_pretrained("facebook/wav2vec2-large-lv60"							)

	UpperCAmelCase_			:	Union[str, Any]      =   load_dataset("patrickvonplaten/librispeech_asr_dummy"     ,							"clean"     ,							split="validation"							)
	UpperCAmelCase_			:	List[str]      =   [x["array"] for x in ds[:4]["audio"]]

	UpperCAmelCase_			:	int      =   processor(_SCREAMING_SNAKE_CASE     ,							return_tensors="pt"     ,							padding=_SCREAMING_SNAKE_CASE							)

	UpperCAmelCase_			:	Union[str, Any]      =   inputs.input_values
	UpperCAmelCase_			:	Dict      =   inputs.attention_mask
	#    input_values = inputs.input_values[:, :-1]
	#    attention_mask = inputs.attention_mask[:, :-1]

	hf_wavavec.eval()
	model.eval()
	if is_finetuned:
		UpperCAmelCase_			:	str      =   model(source=_SCREAMING_SNAKE_CASE     ,							padding_mask=(1 - attention_mask)     ,							mask=_SCREAMING_SNAKE_CASE     ,							features_only=_SCREAMING_SNAKE_CASE							)[
		    "encoder_out"
		].transpose(0     ,							1							)
		UpperCAmelCase_			:	Optional[int]      =   hf_wavavec(_SCREAMING_SNAKE_CASE     ,							attention_mask=_SCREAMING_SNAKE_CASE							)["logits"]

		UpperCAmelCase_			:	Optional[Any]      =   torch.argmax(_SCREAMING_SNAKE_CASE     ,							dim=-1							)
		UpperCAmelCase_			:	Optional[int]      =   processor.batch_decode(_SCREAMING_SNAKE_CASE							)

		print(F'''Expected Output: {ds[:4]["text"]}, Pred: {output_string}'''							)
	else:
		UpperCAmelCase_			:	Union[str, Any]      =   model(source=_SCREAMING_SNAKE_CASE     ,							padding_mask=(1 - attention_mask)     ,							mask=_SCREAMING_SNAKE_CASE     ,							features_only=_SCREAMING_SNAKE_CASE							)[
		    "layer_results"
		][-1][0].transpose(0     ,							1							)
		UpperCAmelCase_			:	Any      =   hf_wavavec(_SCREAMING_SNAKE_CASE     ,							attention_mask=_SCREAMING_SNAKE_CASE							)["last_hidden_state"]

	print(our_output.shape     ,							their_output.shape							)
	UpperCAmelCase_			:	Tuple      =   torch.max(torch.abs(our_output - their_output							)							).item()
	print(F'''max_absolute_diff = {max_absolute_diff}'''							)  # ~ 1e-7
	UpperCAmelCase_			:	Any      =   torch.allclose(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							atol=1E-3							)
	print("Do both models output the same tensors?"     ,							"🔥" if success else "💩"							)
	if not success:
		raise Exception("Something went wRoNg"							)

	hf_wavavec.save_pretrained(_SCREAMING_SNAKE_CASE							)

	if is_finetuned:
		processor.save_pretrained(_SCREAMING_SNAKE_CASE							)
	else:
		processor.feature_extractor.save_pretrained(_SCREAMING_SNAKE_CASE							)


if __name__ == "__main__":
					_lowerCamelCase	 =			argparse.ArgumentParser()
					parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
					parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""")
					parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""")
					parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
					parser.add_argument(
					    """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not"""
					)
					_lowerCamelCase	 =			parser.parse_args()
					convert_wavaveca_checkpoint(
					    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
					)







'''simple docstring'''
import math
from itertools import permutations


def       a__    (  _SCREAMING_SNAKE_CASE					:    int							)			-> bool:


	"""simple docstring"""





	if 1 < number < 4:
		# 2 and 3 are primes
		return True
	elif number < 2 or number % 2 == 0 or number % 3 == 0:
		# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
		return False

	# All primes number are in format of 6k +/- 1
	for i in range(5     ,							int(math.sqrt(_SCREAMING_SNAKE_CASE							) + 1							)     ,							6							):
		if number % i == 0 or number % (i + 2) == 0:
			return False
	return True


def       a__    (  _SCREAMING_SNAKE_CASE					:    int     ,							_SCREAMING_SNAKE_CASE					:    list							)			-> bool:


	"""simple docstring"""





	UpperCAmelCase_ , UpperCAmelCase_			:	Any      =   0, len(_SCREAMING_SNAKE_CASE							) - 1
	while left <= right:
		UpperCAmelCase_			:	List[str]      =   (left + right) // 2
		if prime_list[middle] == target:
			return True
		elif prime_list[middle] < target:
			UpperCAmelCase_			:	Dict      =   middle + 1
		else:
			UpperCAmelCase_			:	int      =   middle - 1

	return False


def       a__    (  )			-> Tuple:


	"""simple docstring"""





	UpperCAmelCase_			:	Dict      =   [n for n in range(10_01     ,							1_00_00     ,							2							) if is_prime(_SCREAMING_SNAKE_CASE							)]
	UpperCAmelCase_			:	Optional[int]      =   []

	for number in prime_list:
		UpperCAmelCase_			:	Optional[Any]      =   []

		for prime_member in permutations(list(str(_SCREAMING_SNAKE_CASE							)							)							):
			UpperCAmelCase_			:	List[Any]      =   int("".join(_SCREAMING_SNAKE_CASE							)							)

			if prime % 2 == 0:
				continue

			if search(_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE							):
				tmp_numbers.append(_SCREAMING_SNAKE_CASE							)

		tmp_numbers.sort()
		if len(_SCREAMING_SNAKE_CASE							) >= 3:
			candidates.append(_SCREAMING_SNAKE_CASE							)

	UpperCAmelCase_			:	Tuple      =   []
	for candidate in candidates:
		UpperCAmelCase_			:	Union[str, Any]      =   len(_SCREAMING_SNAKE_CASE							)
		UpperCAmelCase_			:	Any      =   False

		for i in range(_SCREAMING_SNAKE_CASE							):
			for j in range(i + 1     ,							_SCREAMING_SNAKE_CASE							):
				for k in range(j + 1     ,							_SCREAMING_SNAKE_CASE							):
					if (
					    abs(candidate[i] - candidate[j]							)
					    == abs(candidate[j] - candidate[k]							)
					    and len({candidate[i], candidate[j], candidate[k]}							) == 3
					):
						passed.append(
						    sorted([candidate[i], candidate[j], candidate[k]]							)							)
						UpperCAmelCase_			:	Optional[Any]      =   True

					if found:
						break
				if found:
					break
			if found:
				break

	UpperCAmelCase_			:	Any      =   set()
	for seq in passed:
		answer.add("".join([str(_SCREAMING_SNAKE_CASE							) for i in seq]							)							)

	return max(int(_SCREAMING_SNAKE_CASE							) for x in answer							)


if __name__ == "__main__":
					print(solution())




