




'''simple docstring'''







import pickle
import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin


A     =get_tests_dir('fixtures/test_sentencepiece.model')


@require_sentencepiece
@require_tokenizers
class 			_a  (	__a							,							unittest.TestCase ):
       __a				:     int   				=					XGLMTokenizer
       __a				:     Any   				=					XGLMTokenizerFast
       __a				:     Any   				=					True
       __a				:     Tuple   				=					True
       def     A      (	self						:	Optional[int]				):



           '''simple docstring'''

           super().setUp()

           # We have a SentencePiece fixture for testing
           UpperCAmelCase			       =		XGLMTokenizer(lowercase   ,				keep_accents=lowercase				)
           tokenizer.save_pretrained(self.tmpdirname				)
       def     A      (	self						:	Any				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''<pad>'''
           UpperCAmelCase			       =		1

           self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase				)   ,				lowercase				)
           self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase				)   ,				lowercase				)
       def     A      (	self						:	str				):



           '''simple docstring'''

           UpperCAmelCase			       =		list(self.get_tokenizer().get_vocab().keys()				)

           self.assertEqual(vocab_keys[0]   ,				'''<s>'''				)
           self.assertEqual(vocab_keys[1]   ,				'''<pad>'''				)
           self.assertEqual(len(lowercase				)   ,				1_008				)
       def     A      (	self						:	str				):



           '''simple docstring'''

           self.assertEqual(self.get_tokenizer().vocab_size   ,				1_008				)
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           UpperCAmelCase			       =		XGLMTokenizer(lowercase   ,				keep_accents=lowercase				)

           UpperCAmelCase			       =		tokenizer.tokenize('''This is a test'''				)
           self.assertListEqual(lowercase   ,				['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']				)

           self.assertListEqual(
               tokenizer.convert_tokens_to_ids(lowercase				)   ,				[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]   ,				)

           UpperCAmelCase			       =		tokenizer.tokenize('''I was born in 92000, and this is falsé.'''				)
           self.assertListEqual(
               lowercase   ,				[
                   SPIECE_UNDERLINE + '''I''',
                   SPIECE_UNDERLINE + '''was''',
                   SPIECE_UNDERLINE + '''b''',
                   '''or''',
                   '''n''',
                   SPIECE_UNDERLINE + '''in''',
                   SPIECE_UNDERLINE + '''''',
                   '''9''',
                   '''2''',
                   '''0''',
                   '''0''',
                   '''0''',
                   ''',''',
                   SPIECE_UNDERLINE + '''and''',
                   SPIECE_UNDERLINE + '''this''',
                   SPIECE_UNDERLINE + '''is''',
                   SPIECE_UNDERLINE + '''f''',
                   '''al''',
                   '''s''',
                   '''é''',
                   '''.''',
               ]   ,				)
           UpperCAmelCase			       =		tokenizer.convert_tokens_to_ids(lowercase				)
           self.assertListEqual(
               lowercase   ,				[
                   value + tokenizer.fairseq_offset
                   for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
               ]   ,				)

           UpperCAmelCase			       =		tokenizer.convert_ids_to_tokens(lowercase				)
           self.assertListEqual(
               lowercase   ,				[
                   SPIECE_UNDERLINE + '''I''',
                   SPIECE_UNDERLINE + '''was''',
                   SPIECE_UNDERLINE + '''b''',
                   '''or''',
                   '''n''',
                   SPIECE_UNDERLINE + '''in''',
                   SPIECE_UNDERLINE + '''''',
                   '''<unk>''',
                   '''2''',
                   '''0''',
                   '''0''',
                   '''0''',
                   ''',''',
                   SPIECE_UNDERLINE + '''and''',
                   SPIECE_UNDERLINE + '''this''',
                   SPIECE_UNDERLINE + '''is''',
                   SPIECE_UNDERLINE + '''f''',
                   '''al''',
                   '''s''',
                   '''<unk>''',
                   '''.''',
               ]   ,				)
       @cached_property
       def     A      (	self						:	Any				):



           '''simple docstring'''

           return XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''				)
       def     A      (	self						:	str				):



           '''simple docstring'''

           with tempfile.NamedTemporaryFile() as f:
               shutil.copyfile(lowercase   ,				f.name				)
               UpperCAmelCase			       =		XGLMTokenizer(f.name   ,				keep_accents=lowercase				)
               UpperCAmelCase			       =		pickle.dumps(lowercase				)
           pickle.loads(lowercase				)
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           if not self.test_rust_tokenizer:
               return

           UpperCAmelCase			       =		self.get_tokenizer()
           UpperCAmelCase			       =		self.get_rust_tokenizer()

           UpperCAmelCase			       =		'''I was born in 92000, and this is falsé.'''

           UpperCAmelCase			       =		tokenizer.tokenize(lowercase				)
           UpperCAmelCase			       =		rust_tokenizer.tokenize(lowercase				)
           self.assertListEqual(lowercase   ,				lowercase				)

           UpperCAmelCase			       =		tokenizer.encode(lowercase   ,				add_special_tokens=lowercase				)
           UpperCAmelCase			       =		rust_tokenizer.encode(lowercase   ,				add_special_tokens=lowercase				)
           self.assertListEqual(lowercase   ,				lowercase				)

           UpperCAmelCase			       =		self.get_rust_tokenizer()
           UpperCAmelCase			       =		tokenizer.encode(lowercase				)
           UpperCAmelCase			       =		rust_tokenizer.encode(lowercase				)
           self.assertListEqual(lowercase   ,				lowercase				)
       @slow
       def     A      (	self						:	List[Any]				):



           '''simple docstring'''

           UpperCAmelCase			       =		'''Hello World!'''
           UpperCAmelCase			       =		[2, 31_227, 4_447, 35]

           self.assertListEqual(lowercase   ,				self.big_tokenizer.encode(lowercase				)				)
       @slow
       def     A      (	self						:	int				):



           '''simple docstring'''

           UpperCAmelCase			       =		(
               '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'''
               ''' add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth'''
           )
           # fmt: off
           UpperCAmelCase			       =		[2, 1_018, 67, 11, 1_988, 2_617, 5_631, 278, 11, 3_407, 48, 71_630, 28_085, 4, 3_234, 157, 13, 6, 5, 6, 4, 3_526, 768, 15, 659, 57, 298, 3_983, 864, 129, 21, 6, 5, 13_675, 377, 652, 7_580, 10_341, 155, 2_817, 422, 1_666, 7, 1_674, 53, 113, 202_277, 17_892, 33, 60, 87, 4, 3_234, 157, 61, 2_667, 52_376, 19, 88, 23, 735]
           # fmt: on

           self.assertListEqual(lowercase   ,				self.big_tokenizer.encode(lowercase				)				)







       @slow
       def     A      (	self						:	List[str]				):



           '''simple docstring'''

           UpperCAmelCase			       =		{
               '''input_ids''': [[2, 108_825, 1_163, 15, 88_010, 473, 15_898, 157, 13_672, 1_857, 312, 8, 238_021, 1_163, 53, 13_672, 1_857, 312, 8, 53_283, 182_396, 8, 18_566, 16, 36_733, 4_101, 8, 230, 244_017, 122_553, 7, 15, 132_597, 4, 293, 12_511, 7_610, 4, 3_414, 132_597, 9, 4, 32_361, 362, 4, 734, 28_512, 32_569, 18, 4, 32_361, 26_096, 14_982, 73, 18_715, 21_433, 235_261, 15, 492, 12_427, 16, 53, 18_715, 21_433, 65_454, 15, 23_659, 563, 16, 278, 597, 2_843, 595, 7_931, 182_396, 64_186, 22, 886, 595, 132_981, 53, 25_540, 3_449, 43_982, 39_901, 5_951, 878, 330, 4, 27_694, 80_269, 312, 53, 6_517, 11_780, 611, 20_408, 5], [2, 6, 132_597, 67, 42_897, 33, 592, 8, 163_729, 25_540, 361, 136_997, 109_514, 173_230, 7, 501, 60, 102_913, 196, 5_631, 235, 63_243, 473, 6, 231_757, 74, 5_277, 7_905, 53, 3_095, 37_317, 22, 454, 183_874, 5], [2, 268, 31_298, 46_530, 6, 132_935, 43_831, 7, 597, 32, 24, 3_688, 9_865, 5]],
               '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
           }  # noqa: E501
           # fmt: on

           self.tokenizer_integration_test_util(
               expected_encoding=lowercase   ,				model_name='''facebook/xglm-564M'''   ,				padding=lowercase   ,				)










'''simple docstring'''







import argparse
import json
from pathlib import Path

import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download

from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging


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





def 						snake_case_							(_a	:							List[str]     ):
    UpperCAmelCase			       =		ASTConfig()

    if "10-10" in model_name:
        pass
    elif "speech-commands" in model_name:
        UpperCAmelCase			       =		1_2_8
    elif "12-12" in model_name:
        UpperCAmelCase			       =		1_2
        UpperCAmelCase			       =		1_2
    elif "14-14" in model_name:
        UpperCAmelCase			       =		1_4
        UpperCAmelCase			       =		1_4
    elif "16-16" in model_name:
        UpperCAmelCase			       =		1_6
        UpperCAmelCase			       =		1_6
    else:
        raise ValueError('''Model not supported'''     )

    UpperCAmelCase			       =		'''huggingface/label-files'''
    if "speech-commands" in model_name:
        UpperCAmelCase			       =		3_5
        UpperCAmelCase			       =		'''speech-commands-v2-id2label.json'''
    else:
        UpperCAmelCase			       =		5_2_7
        UpperCAmelCase			       =		'''audioset-id2label.json'''

    UpperCAmelCase			       =		json.load(open(hf_hub_download(_a    ,   _a    ,   repo_type='''dataset'''     )    ,   '''r'''     )     )
    UpperCAmelCase			       =		{int(_a     ): v for k, v in idalabel.items()}
    UpperCAmelCase			       =		idalabel
    UpperCAmelCase			       =		{v: k for k, v in idalabel.items()}

    return config





def 						snake_case_							(_a	:							Tuple     ):
    if "module.v" in name:
        UpperCAmelCase			       =		name.replace('''module.v'''    ,   '''audio_spectrogram_transformer'''     )
    if "cls_token" in name:
        UpperCAmelCase			       =		name.replace('''cls_token'''    ,   '''embeddings.cls_token'''     )
    if "dist_token" in name:
        UpperCAmelCase			       =		name.replace('''dist_token'''    ,   '''embeddings.distillation_token'''     )
    if "pos_embed" in name:
        UpperCAmelCase			       =		name.replace('''pos_embed'''    ,   '''embeddings.position_embeddings'''     )
    if "patch_embed.proj" in name:
        UpperCAmelCase			       =		name.replace('''patch_embed.proj'''    ,   '''embeddings.patch_embeddings.projection'''     )
    # transformer blocks
    if "blocks" in name:
        UpperCAmelCase			       =		name.replace('''blocks'''    ,   '''encoder.layer'''     )
    if "attn.proj" in name:
        UpperCAmelCase			       =		name.replace('''attn.proj'''    ,   '''attention.output.dense'''     )
    if "attn" in name:
        UpperCAmelCase			       =		name.replace('''attn'''    ,   '''attention.self'''     )
    if "norm1" in name:
        UpperCAmelCase			       =		name.replace('''norm1'''    ,   '''layernorm_before'''     )
    if "norm2" in name:
        UpperCAmelCase			       =		name.replace('''norm2'''    ,   '''layernorm_after'''     )
    if "mlp.fc1" in name:
        UpperCAmelCase			       =		name.replace('''mlp.fc1'''    ,   '''intermediate.dense'''     )
    if "mlp.fc2" in name:
        UpperCAmelCase			       =		name.replace('''mlp.fc2'''    ,   '''output.dense'''     )
    # final layernorm
    if "audio_spectrogram_transformer.norm" in name:
        UpperCAmelCase			       =		name.replace('''audio_spectrogram_transformer.norm'''    ,   '''audio_spectrogram_transformer.layernorm'''     )
    # classifier head
    if "module.mlp_head.0" in name:
        UpperCAmelCase			       =		name.replace('''module.mlp_head.0'''    ,   '''classifier.layernorm'''     )
    if "module.mlp_head.1" in name:
        UpperCAmelCase			       =		name.replace('''module.mlp_head.1'''    ,   '''classifier.dense'''     )

    return name





def 						snake_case_							(_a	:							Dict    ,   _a	:							List[Any]     ):
    for key in orig_state_dict.copy().keys():
        UpperCAmelCase			       =		orig_state_dict.pop(_a     )

        if "qkv" in key:
            UpperCAmelCase			       =		key.split('''.'''     )
            UpperCAmelCase			       =		int(key_split[3]     )
            UpperCAmelCase			       =		config.hidden_size
            if "weight" in key:
                UpperCAmelCase			       =		val[:dim, :]
                UpperCAmelCase			       =		val[dim : dim * 2, :]
                UpperCAmelCase			       =		val[-dim:, :]
            else:
                UpperCAmelCase			       =		val[:dim]
                UpperCAmelCase			       =		val[dim : dim * 2]
                UpperCAmelCase			       =		val[-dim:]
        else:
            UpperCAmelCase			       =		val

    return orig_state_dict





def 						snake_case_							(_a	:							Tuple     ):
    UpperCAmelCase			       =		[
        '''module.v.head.weight''',
        '''module.v.head.bias''',
        '''module.v.head_dist.weight''',
        '''module.v.head_dist.bias''',
    ]
    for k in ignore_keys:
        state_dict.pop(_a    ,   _a     )





@torch.no_grad()
def 						snake_case_							(_a	:							int    ,   _a	:							Union[str, Any]    ,   _a	:							Dict=False     ):
    UpperCAmelCase			       =		get_audio_spectrogram_transformer_config(_a     )

    UpperCAmelCase			       =		{
        '''ast-finetuned-audioset-10-10-0.4593''': (
            '''https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'''
        ),
        '''ast-finetuned-audioset-10-10-0.450''': (
            '''https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'''
        ),
        '''ast-finetuned-audioset-10-10-0.448''': (
            '''https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'''
        ),
        '''ast-finetuned-audioset-10-10-0.448-v2''': (
            '''https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'''
        ),
        '''ast-finetuned-audioset-12-12-0.447''': (
            '''https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'''
        ),
        '''ast-finetuned-audioset-14-14-0.443''': (
            '''https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'''
        ),
        '''ast-finetuned-audioset-16-16-0.442''': (
            '''https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'''
        ),
        '''ast-finetuned-speech-commands-v2''': (
            '''https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'''
        ),
    }

    # load original state_dict
    UpperCAmelCase			       =		model_name_to_url[model_name]
    UpperCAmelCase			       =		torch.hub.load_state_dict_from_url(_a    ,   map_location='''cpu'''     )
    # remove some keys
    remove_keys(_a     )
    # rename some keys
    UpperCAmelCase			       =		convert_state_dict(_a    ,   _a     )

    # load 🤗 model
    UpperCAmelCase			       =		ASTForAudioClassification(_a     )
    model.eval()

    model.load_state_dict(_a     )

    # verify outputs on dummy input
    # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
    UpperCAmelCase			       =		-4.267_7393 if '''speech-commands''' not in model_name else -6.84_5978
    UpperCAmelCase			       =		4.568_9974 if '''speech-commands''' not in model_name else 5.565_4526
    UpperCAmelCase			       =		1_0_2_4 if '''speech-commands''' not in model_name else 1_2_8
    UpperCAmelCase			       =		ASTFeatureExtractor(mean=_a    ,   std=_a    ,   max_length=_a     )

    if "speech-commands" in model_name:
        UpperCAmelCase			       =		load_dataset('''speech_commands'''    ,   '''v0.02'''    ,   split='''validation'''     )
        UpperCAmelCase			       =		dataset[0]['''audio''']['''array''']
    else:
        UpperCAmelCase			       =		hf_hub_download(
            repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''    ,   filename='''sample_audio.flac'''    ,   repo_type='''dataset'''    ,   )

        UpperCAmelCase       ,     UpperCAmelCase			       =		torchaudio.load(_a     )
        UpperCAmelCase			       =		waveform.squeeze().numpy()

    UpperCAmelCase			       =		feature_extractor(_a    ,   sampling_rate=1_6_0_0_0    ,   return_tensors='''pt'''     )

    # forward pass
    UpperCAmelCase			       =		model(**_a     )
    UpperCAmelCase			       =		outputs.logits

    if model_name == "ast-finetuned-audioset-10-10-0.4593":
        UpperCAmelCase			       =		torch.tensor([-0.8760, -7.0042, -8.6602]     )
    elif model_name == "ast-finetuned-audioset-10-10-0.450":
        UpperCAmelCase			       =		torch.tensor([-1.1986, -7.0903, -8.2718]     )
    elif model_name == "ast-finetuned-audioset-10-10-0.448":
        UpperCAmelCase			       =		torch.tensor([-2.6128, -8.0080, -9.4344]     )
    elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
        UpperCAmelCase			       =		torch.tensor([-1.5080, -7.4534, -8.8917]     )
    elif model_name == "ast-finetuned-audioset-12-12-0.447":
        UpperCAmelCase			       =		torch.tensor([-0.5050, -6.5833, -8.0843]     )
    elif model_name == "ast-finetuned-audioset-14-14-0.443":
        UpperCAmelCase			       =		torch.tensor([-0.3826, -7.0336, -8.2413]     )
    elif model_name == "ast-finetuned-audioset-16-16-0.442":
        UpperCAmelCase			       =		torch.tensor([-1.2113, -6.9101, -8.3470]     )
    elif model_name == "ast-finetuned-speech-commands-v2":
        UpperCAmelCase			       =		torch.tensor([6.1589, -8.0566, -8.7984]     )
    else:
        raise ValueError('''Unknown model name'''     )
    if not torch.allclose(logits[0, :3]    ,   _a    ,   atol=1E-4     ):
        raise ValueError('''Logits don\'t match'''     )
    print('''Looks ok!'''     )

    if pytorch_dump_folder_path is not None:
        Path(_a     ).mkdir(exist_ok=_a     )
        print(F"Saving model {model_name} to {pytorch_dump_folder_path}"     )
        model.save_pretrained(_a     )
        print(F"Saving feature extractor to {pytorch_dump_folder_path}"     )
        feature_extractor.save_pretrained(_a     )

    if push_to_hub:
        print('''Pushing model and feature extractor to the hub...'''     )
        model.push_to_hub(F"MIT/{model_name}"     )
        feature_extractor.push_to_hub(F"MIT/{model_name}"     )


if __name__ == "__main__":
   A     =argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       '--model_name',
       default='ast-finetuned-audioset-10-10-0.4593',
       type=str,
       help='Name of the Audio Spectrogram Transformer model you\'d like to convert.',
   )
   parser.add_argument(
       '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
   )
   parser.add_argument(
       '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
   )

   A     =parser.parse_args()
   convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)




