




import argparse
import json
import os

import fairseq
import torch
from fairseq.data import Dictionary

from transformers import (
    UniSpeechConfig,
    UniSpeechForCTC,
    UniSpeechForPreTraining,
    WavaVecaFeatureExtractor,
    WavaVecaPhonemeCTCTokenizer,
    WavaVecaProcessor,
    logging,
)


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

__a    :						List[str]						      =       {
    '''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_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    :						List[str]						      =       [
    '''ctc_proj''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]
def    snake_case_	(						SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							)     ->					List[str]:
							for attribute in key.split("."							):
														if is_finetuned:
																					if attribute in ["quantizer", "project_q", "project_hid"]:
																												# those layers are only relevant for pretraining and should be dropped
																												return

																					if attribute == "ctc_proj":
																												# we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models
																												lowercase__    :			List[Any]     =				"lm_head"

														lowercase__    :			Optional[int]     =				getattr(__lowerCamelCase							,__lowerCamelCase							)

							if weight_type is not None:
														lowercase__    :			int     =				getattr(__lowerCamelCase							,__lowerCamelCase							).shape
							else:
														lowercase__    :			Optional[int]     =				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":
														lowercase__    :			int     =				value
							elif weight_type == "weight_g":
														lowercase__    :			Dict     =				value
							elif weight_type == "weight_v":
														lowercase__    :			Any     =				value
							elif weight_type == "bias":
														lowercase__    :			List[Any]     =				value
							else:
														lowercase__    :			Optional[int]     =				value

							logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}."""							)
def    snake_case_	(						SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							)     ->					Union[str, Any]:
							lowercase__    :			List[str]     =				[]
							lowercase__    :			List[Any]     =				fairseq_model.state_dict()

							lowercase__    :			List[Any]     =				hf_model.unispeech.feature_extractor

							for name, value in fairseq_dict.items():
														lowercase__    :			Optional[Any]     =				False
														if "conv_layers" in name:
																					load_conv_layer(
																					    __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,hf_model.config.feat_extract_norm == "group"							,)
																					lowercase__    :			Any     =				True
														else:
																					for key, mapped_key in MAPPING.items():
																												lowercase__    :			Any     =				"unispeech." + 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]:
																																			lowercase__    :			Optional[Any]     =				True
																																			if "*" in mapped_key:
																																										lowercase__    :			Tuple     =				name.split(__lowerCamelCase							)[0].split("."							)[-2]
																																										lowercase__    :			List[str]     =				mapped_key.replace("*"							,__lowerCamelCase							)
																																			if "weight_g" in name:
																																										lowercase__    :			Dict     =				"weight_g"
																																			elif "weight_v" in name:
																																										lowercase__    :			Union[str, Any]     =				"weight_v"
																																			elif "bias" in name:
																																										lowercase__    :			Optional[Any]     =				"bias"
																																			elif "weight" in name:
																																										# TODO: don't match quantizer.weight_proj
																																										lowercase__    :			Optional[Any]     =				"weight"
																																			else:
																																										lowercase__    :			int     =				None
																																			set_recursively(__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							)
																												continue
														if not is_used:
																					unused_weights.append(__lowerCamelCase							)

							logger.warning(F"""Unused weights: {unused_weights}"""							)
def    snake_case_	(						SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							)     ->					int:
							lowercase__    :			List[str]     =				full_name.split("conv_layers."							)[-1]
							lowercase__    :			Dict     =				name.split("."							)
							lowercase__    :			Optional[int]     =				int(items[0]							)
							lowercase__    :			int     =				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."""
																					)
																					lowercase__    :			Dict     =				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."""
																					)
																					lowercase__    :			List[str]     =				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."
																					)
																					lowercase__    :			Any     =				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."""
																					)
																					lowercase__    :			Union[str, Any]     =				value
																					logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}."""							)
							else:
														unused_weights.append(__lowerCamelCase							)
@torch.no_grad()
def    snake_case_	(						SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_							,SCREAMING_SNAKE_CASE_=None							,SCREAMING_SNAKE_CASE_=None							,SCREAMING_SNAKE_CASE_=True							)     ->					List[Any]:
							if config_path is not None:
														lowercase__    :			Any     =				UniSpeechConfig.from_pretrained(__lowerCamelCase							)
							else:
														lowercase__    :			Tuple     =				UniSpeechConfig()

							if is_finetuned:
														if dict_path:
																					lowercase__    :			List[Any]     =				Dictionary.load_from_json(__lowerCamelCase							)

																					# important change bos & pad token id since CTC symbol is <pad> and
																					# not <s> as in fairseq
																					lowercase__    :			str     =				target_dict.pad_index
																					lowercase__    :			List[str]     =				target_dict.bos_index
																					lowercase__    :			Any     =				target_dict.eos_index
																					lowercase__    :			int     =				len(target_dict.symbols							)
																					lowercase__    :			Tuple     =				os.path.join(__lowerCamelCase							,"vocab.json"							)
																					if not os.path.isdir(__lowerCamelCase							):
																												logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(__lowerCamelCase							)							)
																												return
																					os.makedirs(__lowerCamelCase							,exist_ok=__lowerCamelCase							)
																					lowercase__    :			Optional[int]     =				target_dict.indices

																					# fairseq has the <pad> and <s> switched
																					lowercase__    :			Any     =				42
																					lowercase__    :			Optional[Any]     =				43
																					with open(__lowerCamelCase							,"w"							,encoding="utf-8"							) as vocab_handle:
																												json.dump(__lowerCamelCase							,__lowerCamelCase							)
																					lowercase__    :			str     =				WavaVecaPhonemeCTCTokenizer(
																					    __lowerCamelCase							,unk_token=target_dict.unk_word							,pad_token=target_dict.pad_word							,bos_token=target_dict.bos_word							,eos_token=target_dict.eos_word							,word_delimiter_token="|"							,do_lower_case=__lowerCamelCase							,)
																					lowercase__    :			int     =				True if config.feat_extract_norm == "layer" else False
																					lowercase__    :			List[Any]     =				WavaVecaFeatureExtractor(
																					    feature_size=1							,sampling_rate=1_60_00							,padding_value=0							,do_normalize=__lowerCamelCase							,return_attention_mask=__lowerCamelCase							,)
																					lowercase__    :			str     =				WavaVecaProcessor(feature_extractor=__lowerCamelCase							,tokenizer=__lowerCamelCase							)
																					processor.save_pretrained(__lowerCamelCase							)

														lowercase__    :			List[str]     =				UniSpeechForCTC(__lowerCamelCase							)
							else:
														lowercase__    :			Tuple     =				UniSpeechForPreTraining(__lowerCamelCase							)

							if is_finetuned:
														lowercase__   ,  lowercase__   ,  lowercase__    :			str     =				fairseq.checkpoint_utils.load_model_ensemble_and_task(
														    [checkpoint_path]							,arg_overrides={"data": "/".join(dict_path.split("/"							)[:-1]							), "w2v_path": checkpoint_path}							)
							else:
														lowercase__   ,  lowercase__   ,  lowercase__    :			int     =				fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path]							)

							lowercase__    :			Optional[int]     =				model[0].eval()

							recursively_load_weights(__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							)

							hf_unispeech.save_pretrained(__lowerCamelCase							)


if __name__ == "__main__":
						__a    :						Dict						      =       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'''
						)
						__a    :						List[Any]						      =       parser.parse_args()
						convert_unispeech_checkpoint(
						    args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
						)




import unittest

from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
				from PIL import Image
else:






				class     __a			:



					@staticmethod
					def 		UpperCamelCase				(    *snake_case_				:     Any					,						**snake_case_				:     str)->				int:
										pass






@is_pipeline_test
@require_vision
class     __a			(  unittest.TestCase					):



	@require_torch
	def 		UpperCamelCase				(    self				:     Dict)->				List[str]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						)
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""a""", """b""", """c"""])

						# The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
						# python and torch versions.
						self.assertIn(
						    nested_simplify(snake_case_)					,						[
						        [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}],
						        [{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """c"""}, {"""score""": 0.3_3_3, """label""": """b"""}],
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""A""", """B""", """C"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						    ]					,						)



	@require_tf
	def 		UpperCamelCase				(    self				:     Dict)->				Optional[Any]:
						__lowerCAmelCase						 =pipeline(
						    model="""hf-internal-testing/tiny-random-clip-zero-shot-image-classification"""					,						framework="""tf""")
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""a""", """b""", """c"""])

						self.assertEqual(
						    nested_simplify(snake_case_)					,						[{"""score""": 0.3_3_3, """label""": """a"""}, {"""score""": 0.3_3_3, """label""": """b"""}, {"""score""": 0.3_3_3, """label""": """c"""}]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""A""", """B""", """C"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						        [
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						            {"""score""": 0.3_3_3, """label""": ANY(snake_case_)},
						        ],
						    ]					,						)



	@slow
	@require_torch
	def 		UpperCamelCase				(    self				:     Any)->				Dict:
						__lowerCAmelCase						 =pipeline(
						    task="""zero-shot-image-classification"""					,						model="""openai/clip-vit-base-patch32"""					,						)
						# This is an image of 2 cats with remotes and no planes
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])

						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.5_1_1, """label""": """remote"""},
						            {"""score""": 0.4_8_5, """label""": """cat"""},
						            {"""score""": 0.0_0_4, """label""": """plane"""},
						        ],
						    ]
						    * 5					,						)



	@slow
	@require_tf
	def 		UpperCamelCase				(    self				:     Optional[int])->				int:
						__lowerCAmelCase						 =pipeline(
						    task="""zero-shot-image-classification"""					,						model="""openai/clip-vit-base-patch32"""					,						framework="""tf""")
						# This is an image of 2 cats with remotes and no planes
						__lowerCAmelCase						 =Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
						__lowerCAmelCase						 =image_classifier(snake_case_					,						candidate_labels=["""cat""", """plane""", """remote"""])
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        {"""score""": 0.5_1_1, """label""": """remote"""},
						        {"""score""": 0.4_8_5, """label""": """cat"""},
						        {"""score""": 0.0_0_4, """label""": """plane"""},
						    ]					,						)

						__lowerCAmelCase						 =image_classifier([image] * 5					,						candidate_labels=["""cat""", """plane""", """remote"""]					,						batch_size=2)
						self.assertEqual(
						    nested_simplify(snake_case_)					,						[
						        [
						            {"""score""": 0.5_1_1, """label""": """remote"""},
						            {"""score""": 0.4_8_5, """label""": """cat"""},
						            {"""score""": 0.0_0_4, """label""": """plane"""},
						        ],
						    ]
						    * 5					,						)




