


"""simple docstring"""


import argparse

import torch

# Step 1. clone https://github.com/microsoft/unilm
# Step 2. git checkout to https://github.com/microsoft/unilm/commit/b94ec76c36f02fb2b0bf0dcb0b8554a2185173cd
# Step 3. cd unilm
# Step 4. ln -s $(realpath wavlm/modules.py) ./  # create simlink
# import classes
from unilm.wavlm.WavLM import WavLM as WavLMOrig
from unilm.wavlm.WavLM import WavLMConfig as WavLMConfigOrig

from transformers import WavLMConfig, WavLMModel, logging


logging.set_verbosity_info()
A     :   Union[str, Any]			    =			logging.get_logger(__name__)

A     :   Dict			    =			{
    "post_extract_proj": "feature_projection.projection",
    "encoder.pos_conv.0": "encoder.pos_conv_embed.conv",
    "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.grep_linear": "encoder.layers.*.attention.gru_rel_pos_linear",
    "self_attn.relative_attention_bias": "encoder.layers.*.attention.rel_attn_embed",
    "self_attn.grep_a": "encoder.layers.*.attention.gru_rel_pos_const",
    "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",
    "quantizer.weight_proj": "quantizer.weight_proj",
    "quantizer.vars": "quantizer.codevectors",
    "project_q": "project_q",
    "final_proj": "project_hid",
    "w2v_encoder.proj": "ctc_proj",
    "mask_emb": "masked_spec_embed",
}
A     :   Dict			    =			[
    "ctc_proj",
    "quantizer.weight_proj",
    "quantizer.codevectors",
    "project_q",
    "project_hid",
]


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			for attribute in key.split("."      ):
						__lowerCAmelCase				    =			getattr(_UpperCamelCase    , _UpperCamelCase      )

			if weight_type is not None:
						__lowerCAmelCase				    =			getattr(_UpperCamelCase    , _UpperCamelCase      ).shape
			else:
						__lowerCAmelCase				    =			hf_pointer.shape

			assert hf_shape == value.shape, (
			    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":
						__lowerCAmelCase				    =			value
			elif weight_type == "weight_g":
						__lowerCAmelCase				    =			value
			elif weight_type == "weight_v":
						__lowerCAmelCase				    =			value
			elif weight_type == "bias":
						__lowerCAmelCase				    =			value
			else:
						__lowerCAmelCase				    =			value

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


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			[]
			__lowerCAmelCase				    =			fairseq_model.state_dict()

			__lowerCAmelCase				    =			hf_model.feature_extractor

			for name, value in fairseq_dict.items():
						__lowerCAmelCase				    =			False
						if "conv_layers" in name:
									load_conv_layer(
									    _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , hf_model.config.feat_extract_norm == "group"    , )
									__lowerCAmelCase				    =			True
						else:
									for key, mapped_key in MAPPING.items():
												if key in name or key.split("w2v_model."      )[-1] == name.split("."      )[0]:
															__lowerCAmelCase				    =			True
															if "*" in mapped_key:
																		__lowerCAmelCase				    =			name.split(_UpperCamelCase      )[0].split("."      )[-2]
																		__lowerCAmelCase				    =			mapped_key.replace("*"    , _UpperCamelCase      )
															if "weight_g" in name:
																		__lowerCAmelCase				    =			"weight_g"
															elif "weight_v" in name:
																		__lowerCAmelCase				    =			"weight_v"
															elif "bias" in name and "relative_attention_bias" not in name:
																		__lowerCAmelCase				    =			"bias"
															elif "weight" in name:
																		# TODO: don't match quantizer.weight_proj
																		__lowerCAmelCase				    =			"weight"
															else:
																		__lowerCAmelCase				    =			None

															set_recursively(_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      )
												continue
						if not is_used:
									unused_weights.append(_UpperCamelCase      )

			logger.warning(f"Unused weights: {unused_weights}"      )


def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			full_name.split("conv_layers."      )[-1]
			__lowerCAmelCase				    =			name.split("."      )
			__lowerCAmelCase				    =			int(items[0]      )
			__lowerCAmelCase				    =			int(items[1]      )

			if type_id == 0:
						if "bias" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
									    f"{full_name} has size {value.shape}, but"
									    f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
									)
									__lowerCAmelCase				    =			value
									logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}."      )
						elif "weight" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
									    f"{full_name} has size {value.shape}, but"
									    f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
									)
									__lowerCAmelCase				    =			value
									logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}."      )
			elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
						if "bias" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
									    f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
									    " found."
									)
									__lowerCAmelCase				    =			value
									logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."      )
						elif "weight" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
									    f"{full_name} has size {value.shape}, but"
									    f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
									)
									__lowerCAmelCase				    =			value
									logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."      )
			else:
						unused_weights.append(_UpperCamelCase      )


@torch.no_grad()
def _lowerCamelCase	(		_UpperCamelCase    , _UpperCamelCase    , _UpperCamelCase=None      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			torch.load(_UpperCamelCase      )
			__lowerCAmelCase				    =			WavLMConfigOrig(checkpoint["cfg"]      )
			__lowerCAmelCase				    =			WavLMOrig(_UpperCamelCase      )
			model.load_state_dict(checkpoint["model"]      )
			model.eval()

			if config_path is not None:
						__lowerCAmelCase				    =			WavLMConfig.from_pretrained(_UpperCamelCase      )
			else:
						__lowerCAmelCase				    =			WavLMConfig()

			__lowerCAmelCase				    =			WavLMModel(_UpperCamelCase      )

			recursively_load_weights(_UpperCamelCase    , _UpperCamelCase      )

			hf_wavlm.save_pretrained(_UpperCamelCase      )


if __name__ == "__main__":
	A     :   List[str]			    =			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("--config_path", default=None, type=str, help="Path to hf config.json of model to convert")
	A     :   Optional[Any]			    =			parser.parse_args()
	convert_wavlm_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)








"""simple docstring"""


import sys
from collections import defaultdict
class   _UpperCamelCase  :
							'''simple docstring'''







							def __init__(     self	):
										__lowerCAmelCase				    =			[]

							def 			snake_case				(     self    ,   __a	):
										return self.node_position[vertex]

							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			pos

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a    ,   __a	):
										if start > size // 2 - 1:
													return
										else:
													if 2 * start + 2 >= size:
																__lowerCAmelCase				    =			2 * start + 1
													else:
																if heap[2 * start + 1] < heap[2 * start + 2]:
																			__lowerCAmelCase				    =			2 * start + 1
																else:
																			__lowerCAmelCase				    =			2 * start + 2
													if heap[smallest_child] < heap[start]:
																__lowerCAmelCase    ,	__lowerCAmelCase				    =			heap[smallest_child], positions[smallest_child]
																__lowerCAmelCase    ,	__lowerCAmelCase				    =			(
																    heap[start],
																    positions[start],
																)
																__lowerCAmelCase    ,	__lowerCAmelCase				    =			temp, tempa

																__lowerCAmelCase				    =			self.get_position(positions[smallest_child]	)
																self.set_position(
																    positions[smallest_child]    ,   self.get_position(positions[start]	)	)
																self.set_position(positions[start]    ,   __a	)

																self.top_to_bottom(__a    ,   __a    ,   __a    ,   __a	)

							def 			snake_case				(     self    ,   __a    ,   __a    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			position[index]

										while index != 0:
													__lowerCAmelCase				    =			int((index - 2) / 2	) if index % 2 == 0 else int((index - 1) / 2	)

													if val < heap[parent]:
																__lowerCAmelCase				    =			heap[parent]
																__lowerCAmelCase				    =			position[parent]
																self.set_position(position[parent]    ,   __a	)
													else:
																__lowerCAmelCase				    =			val
																__lowerCAmelCase				    =			temp
																self.set_position(__a    ,   __a	)
																break
													__lowerCAmelCase				    =			parent
										else:
													__lowerCAmelCase				    =			val
													__lowerCAmelCase				    =			temp
													self.set_position(__a    ,   0	)

							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			len(__a	) // 2 - 1
										for i in range(__a    ,   -1    ,   -1	):
													self.top_to_bottom(__a    ,   __a    ,   len(__a	)    ,   __a	)



							def 			snake_case				(     self    ,   __a    ,   __a	):
										__lowerCAmelCase				    =			positions[0]
										__lowerCAmelCase				    =			sys.maxsize
										self.top_to_bottom(__a    ,   0    ,   len(__a	)    ,   __a	)
										return temp


def _lowerCamelCase	(		_UpperCamelCase      ):

			'''simple docstring'''




			__lowerCAmelCase				    =			Heap()

			__lowerCAmelCase				    =			[0] * len(_UpperCamelCase      )
			__lowerCAmelCase				    =			[-1] * len(_UpperCamelCase      )  # Neighboring Tree Vertex of selected vertex
			# Minimum Distance of explored vertex with neighboring vertex of partial tree
			# formed in graph
			__lowerCAmelCase				    =			[]  # Heap of Distance of vertices from their neighboring vertex
			__lowerCAmelCase				    =			[]

			for vertex in range(len(_UpperCamelCase      )      ):
						distance_tv.append(sys.maxsize      )
						positions.append(_UpperCamelCase      )
						heap.node_position.append(_UpperCamelCase      )

			__lowerCAmelCase				    =			[]
			__lowerCAmelCase				    =			1
			__lowerCAmelCase				    =			sys.maxsize
			for neighbor, distance in adjacency_list[0]:
						__lowerCAmelCase				    =			0
						__lowerCAmelCase				    =			distance
			heap.heapify(_UpperCamelCase    , _UpperCamelCase      )

			for _ in range(1    , len(_UpperCamelCase      )      ):
						__lowerCAmelCase				    =			heap.delete_minimum(_UpperCamelCase    , _UpperCamelCase      )
						if visited[vertex] == 0:
									tree_edges.append((nbr_tv[vertex], vertex)      )
									__lowerCAmelCase				    =			1
									for neighbor, distance in adjacency_list[vertex]:
												if (
												    visited[neighbor] == 0
												    and distance < distance_tv[heap.get_position(_UpperCamelCase      )]
												):
															__lowerCAmelCase				    =			distance
															heap.bottom_to_top(
															    _UpperCamelCase    , heap.get_position(_UpperCamelCase      )    , _UpperCamelCase    , _UpperCamelCase      )
															__lowerCAmelCase				    =			vertex
			return tree_edges


if __name__ == "__main__":  # pragma: no cover
	# < --------- Prims Algorithm --------- >
	A     :   Optional[Any]			    =			int(input("Enter number of edges: ").strip())
	A     :   Dict			    =			defaultdict(list)
	for _ in range(edges_number):
		A     :   str			    =			[int(x) for x in input().strip().split()]
		adjacency_list[edge[0]].append([edge[1], edge[2]])
		adjacency_list[edge[1]].append([edge[0], edge[2]])
	print(prisms_algorithm(adjacency_list))




