'''simple docstring'''




import io
import os
import unicodedata
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


_A								=   logging.get_logger(__name__)

_A								=   '▁'

_A								=   {'vocab_file': 'vocab.txt', 'sentencepiece_model_ckpt': 'sentencepiece.bpe.model'}

_A								=   {
    'sentencepiece_model_file': 'sentencepiece.bpe.model',
    'vocab_file': 'vocab.txt',
}

_A								=   {
    'vocab_file': {
        'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
        'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt',
    },
    'sentencepiece_model_file': {
        'ernie-m-base': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
        'ernie-m-large': 'https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model',
    },
}

_A								=   {
    'ernie-m-base': 5_1_4,
    'ernie-m-large': 5_1_4,
}

_A								=   {
    'ernie-m-base': {'do_lower_case': False},
    'ernie-m-large': {'do_lower_case': False},
}


class       UpperCAmelCase__  (       _snake_case			):






   """simple docstring"""
   A							:       List[str]     =    ["input_ids"]

   A							:       Optional[Any]     =    VOCAB_FILES_NAMES
   A							:       Dict     =    PRETRAINED_INIT_CONFIGURATION
   A							:       int     =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A							:       List[str]     =    PRETRAINED_VOCAB_FILES_MAP
   A							:       Any     =    RESOURCE_FILES_NAMES
   def __init__(self       ,				_a       ,				_a=None       ,				_a=False       ,				_a="utf8"       ,				_a="[UNK]"       ,				_a="[SEP]"       ,				_a="[PAD]"       ,				_a="[CLS]"       ,				_a="[MASK]"       ,				_a = None       ,				**_a       ,				)    ->     None:
        # Mask token behave like a normal word, i.e. include the space before it and
        # is included in the raw text, there should be a match in a non-normalized sentence.

        lowercase_					:       Optional[Any]     				=					{} if sp_model_kwargs is None else sp_model_kwargs
        super().__init__(
            do_lower_case=_a       ,				unk_token=_a       ,				sep_token=_a       ,				pad_token=_a       ,				cls_token=_a       ,				mask_token=_a       ,				vocab_file=_a       ,				encoding=_a       ,				sp_model_kwargs=self.sp_model_kwargs       ,				**_a       ,				)
        lowercase_					:       int     				=					do_lower_case
        lowercase_					:       str     				=					sentencepiece_model_ckpt
        lowercase_					:       Tuple     				=					spm.SentencePieceProcessor(**self.sp_model_kwargs				)
        self.sp_model.Load(_a				)

        # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
        if vocab_file is not None:
             lowercase_					:       Union[str, Any]     				=					self.load_vocab(filepath=_a				)
        else:
             lowercase_					:       Any     				=					{self.sp_model.id_to_piece(_a				): id for id in range(self.sp_model.get_piece_size()				)}
        lowercase_					:       Optional[int]     				=					{v: k for k, v in self.vocab.items()}
   def 		_lowerCamelCase (self       ,				_a				)    ->     Any:
        if text is None:
             return None

        lowercase_					:       Dict     				=					self.tokenize(_a				)
        lowercase_				,lowercase_					:       Dict     				=					'', []

        for i, ch in enumerate(_a				):
             if ch in self.SP_CHAR_MAPPING:
                  lowercase_					:       str     				=					self.SP_CHAR_MAPPING.get(_a				)
             else:
                  lowercase_					:       List[str]     				=					unicodedata.normalize('NFKC'       ,				_a				)
             if self.is_whitespace(_a				):
                  continue
             normalized_text += ch
             char_mapping.extend([i] * len(_a				)				)

        lowercase_				,lowercase_				,lowercase_					:       int     				=					normalized_text, [], 0

        if self.do_lower_case:
             lowercase_					:       Optional[Any]     				=					text.lower()

        for token in split_tokens:
             if token[:1] == "▁":
                  lowercase_					:       Tuple     				=					token[1:]
             lowercase_					:       List[str]     				=					text[offset:].index(_a				) + offset
             lowercase_					:       Any     				=					start + len(_a				)

             token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1)				)
             lowercase_					:       Tuple     				=					end
        return token_mapping
   @property
   def 		_lowerCamelCase (self				)    ->     List[Any]:
        return len(self.vocab				)
   def 		_lowerCamelCase (self				)    ->     int:
        return dict(self.vocab       ,				**self.added_tokens_encoder				)
   def __getstate__(self				)    ->     Optional[Any]:
        lowercase_					:       Dict     				=					self.__dict__.copy()
        lowercase_					:       List[str]     				=					None
        return state
   def __setstate__(self       ,				_a				)    ->     Any:
        lowercase_					:       Optional[int]     				=					d

        # for backward compatibility
        if not hasattr(self       ,				'sp_model_kwargs'				):
             lowercase_					:       Tuple     				=					{}

        lowercase_					:       Optional[int]     				=					spm.SentencePieceProcessor(**self.sp_model_kwargs				)
        self.sp_model.Load(self.sentencepiece_model_ckpt				)
   def 		_lowerCamelCase (self       ,				_a				)    ->     str:
        return "".join((self.SP_CHAR_MAPPING.get(_a       ,				_a				) for c in text)				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a=False       ,				_a=64       ,				_a=0.1				)    ->     Optional[int]:

        if self.sp_model_kwargs.get('enable_sampling'				) is True:
             lowercase_					:       Optional[int]     				=					True
        if self.sp_model_kwargs.get('alpha'				) is not None:
             lowercase_					:       Union[str, Any]     				=					self.sp_model_kwargs.get('alpha'				)
        if self.sp_model_kwargs.get('nbest_size'				) is not None:
             lowercase_					:       Optional[int]     				=					self.sp_model_kwargs.get('nbest_size'				)

        if not enable_sampling:
             lowercase_					:       Optional[Any]     				=					self.sp_model.EncodeAsPieces(_a				)
        else:
             lowercase_					:       List[Any]     				=					self.sp_model.SampleEncodeAsPieces(_a       ,				_a       ,				_a				)
        lowercase_					:       int     				=					[]
        for pi, piece in enumerate(_a				):
             if piece == SPIECE_UNDERLINE:
                  if not pieces[pi + 1].startswith(_a				) and pi != 0:
                       new_pieces.append(_a				)
                       continue
                  else:
                       continue
             lowercase_					:       Optional[Any]     				=					0
             for i, chunk in enumerate(_a				):
                  if chunk == SPIECE_UNDERLINE:
                       continue
                  if self.is_ch_char(_a				) or self.is_punct(_a				):
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]				)
                       new_pieces.append(_a				)
                       lowercase_					:       List[Any]     				=					i + 1
                  elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]				)
                       lowercase_					:       Optional[Any]     				=					i
                  elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
                       if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
                            new_pieces.append(piece[lst_i:i]				)
                       lowercase_					:       int     				=					i
             if len(_a				) > lst_i:
                  new_pieces.append(piece[lst_i:]				)
        return new_pieces
   def 		_lowerCamelCase (self       ,				_a				)    ->     Union[str, Any]:
        lowercase_					:       Optional[Any]     				=					''.join(_a				).replace(_a       ,				' '				).strip()
        return out_string
   def 		_lowerCamelCase (self       ,				_a				)    ->     Optional[int]:
        lowercase_					:       Optional[Any]     				=					self.convert_ids_to_tokens(_a				)
        lowercase_					:       Tuple     				=					''.join(_a				).replace(_a       ,				' '				).strip()
        return out_string
   def 		_lowerCamelCase (self       ,				_a				)    ->     Optional[int]:
        return self.vocab.get(_a       ,				self.vocab.get(self.unk_token				)				)
   def 		_lowerCamelCase (self       ,				_a				)    ->     int:
        return self.reverse_vocab.get(_a       ,				self.unk_token				)
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None				)    ->     Any:
        if token_ids_a is None:
             return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
        lowercase_					:       Tuple     				=					[self.cls_token_id]
        lowercase_					:       int     				=					[self.sep_token_id]
        return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None				)    ->     Optional[Any]:
        if offset_mapping_a is None:
             return [(0, 0)] + offset_mapping_a + [(0, 0)]

        return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)]
   def 		_lowerCamelCase (self       ,				_a       ,				_a=None       ,				_a=False				)    ->     Union[str, Any]:

        if already_has_special_tokens:
             if token_ids_a is not None:
                  raise ValueError(
                      'You should not supply a second sequence if the provided sequence of '
                      'ids is already formatted with special tokens for the model.'				)
             return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

        if token_ids_a is not None:
             return [1] + ([0] * len(_a				)) + [1, 1] + ([0] * len(_a				)) + [1]
        return [1] + ([0] * len(_a				)) + [1]
   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     List[int]:
        # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
        if token_ids_a is None:
             # [CLS] X [SEP]
             return (len(_a				) + 2) * [0]

        # [CLS] A [SEP] [SEP] B [SEP]
        return [0] * (len(_a				) + 1) + [1] * (len(_a				) + 3)
   def 		_lowerCamelCase (self       ,				_a				)    ->     int:
        if "\u4e00" <= char <= "\u9fff":
             return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     List[str]:
        if ("a" <= char <= "z") or ("A" <= char <= "Z"):
             return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     int:
        if char in ",;:.?!~，；：。？！《》【】":
             return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     List[Any]:
        if char == " " or char == "\t" or char == "\n" or char == "\r":
             return True
        if len(_a				) == 1:
             lowercase_					:       Optional[Any]     				=					unicodedata.category(_a				)
             if cat == "Zs":
                  return True
        return False
   def 		_lowerCamelCase (self       ,				_a				)    ->     Tuple:
        lowercase_					:       List[Any]     				=					{}
        with io.open(_a       ,				'r'       ,				encoding='utf-8'				) as f:
             for index, line in enumerate(_a				):
                  lowercase_					:       Dict     				=					line.rstrip('\n'				)
                  lowercase_					:       Dict     				=					int(_a				)

        return token_to_idx





   def 		_lowerCamelCase (self       ,				_a       ,				_a = None				)    ->     Tuple[str]:
        lowercase_					:       Tuple     				=					0
        if os.path.isdir(_a				):
             lowercase_					:       Any     				=					os.path.join(
                 _a       ,				(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']				)
        else:
             lowercase_					:       Tuple     				=					(filename_prefix + '-' if filename_prefix else '') + save_directory
        with open(_a       ,				'w'       ,				encoding='utf-8'				) as writer:
             for token, token_index in sorted(self.vocab.items()       ,				key=lambda _a				: kv[1]				):
                  if index != token_index:
                       logger.warning(
                           f'''Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.'''
                           ' Please check that the vocabulary is not corrupted!'				)
                       lowercase_					:       Tuple     				=					token_index
                  writer.write(token + '\n'				)
                  index += 1

        lowercase_					:       List[str]     				=					os.path.join(_a       ,				'sentencepiece.bpe.model'				)
        with open(_a       ,				'wb'				) as fi:
             lowercase_					:       Tuple     				=					self.sp_model.serialized_model_proto()
             fi.write(_a				)

        return (vocab_file,)





'''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 _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       List[Any]     				=					ASTConfig()

     if "10-10" in model_name:
          pass
     elif "speech-commands" in model_name:
          lowercase_					:       List[Any]     				=					128
     elif "12-12" in model_name:
          lowercase_					:       Tuple     				=					12
          lowercase_					:       List[Any]     				=					12
     elif "14-14" in model_name:
          lowercase_					:       List[str]     				=					14
          lowercase_					:       Optional[Any]     				=					14
     elif "16-16" in model_name:
          lowercase_					:       Union[str, Any]     				=					16
          lowercase_					:       List[str]     				=					16
     else:
          raise ValueError('Model not supported'							)

     lowercase_					:       Optional[Any]     				=					'huggingface/label-files'
     if "speech-commands" in model_name:
          lowercase_					:       List[str]     				=					35
          lowercase_					:       int     				=					'speech-commands-v2-id2label.json'
     else:
          lowercase_					:       Union[str, Any]     				=					527
          lowercase_					:       int     				=					'audioset-id2label.json'

     lowercase_					:       Union[str, Any]     				=					json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       repo_type='dataset'							)  ,       'r'							)							)
     lowercase_					:       Union[str, Any]     				=					{int(SCREAMING_SNAKE_CASE_							): v for k, v in idalabel.items()}
     lowercase_					:       Optional[int]     				=					idalabel
     lowercase_					:       Optional[int]     				=					{v: k for k, v in idalabel.items()}

     return config

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     if "module.v" in name:
          lowercase_					:       Dict     				=					name.replace('module.v'  ,       'audio_spectrogram_transformer'							)
     if "cls_token" in name:
          lowercase_					:       Optional[Any]     				=					name.replace('cls_token'  ,       'embeddings.cls_token'							)
     if "dist_token" in name:
          lowercase_					:       Any     				=					name.replace('dist_token'  ,       'embeddings.distillation_token'							)
     if "pos_embed" in name:
          lowercase_					:       List[str]     				=					name.replace('pos_embed'  ,       'embeddings.position_embeddings'							)
     if "patch_embed.proj" in name:
          lowercase_					:       int     				=					name.replace('patch_embed.proj'  ,       'embeddings.patch_embeddings.projection'							)
     # transformer blocks
     if "blocks" in name:
          lowercase_					:       Optional[Any]     				=					name.replace('blocks'  ,       'encoder.layer'							)
     if "attn.proj" in name:
          lowercase_					:       Optional[int]     				=					name.replace('attn.proj'  ,       'attention.output.dense'							)
     if "attn" in name:
          lowercase_					:       Dict     				=					name.replace('attn'  ,       'attention.self'							)
     if "norm1" in name:
          lowercase_					:       int     				=					name.replace('norm1'  ,       'layernorm_before'							)
     if "norm2" in name:
          lowercase_					:       Optional[int]     				=					name.replace('norm2'  ,       'layernorm_after'							)
     if "mlp.fc1" in name:
          lowercase_					:       Optional[int]     				=					name.replace('mlp.fc1'  ,       'intermediate.dense'							)
     if "mlp.fc2" in name:
          lowercase_					:       int     				=					name.replace('mlp.fc2'  ,       'output.dense'							)
     # final layernorm
     if "audio_spectrogram_transformer.norm" in name:
          lowercase_					:       int     				=					name.replace('audio_spectrogram_transformer.norm'  ,       'audio_spectrogram_transformer.layernorm'							)
     # classifier head
     if "module.mlp_head.0" in name:
          lowercase_					:       Dict     				=					name.replace('module.mlp_head.0'  ,       'classifier.layernorm'							)
     if "module.mlp_head.1" in name:
          lowercase_					:       List[Any]     				=					name.replace('module.mlp_head.1'  ,       'classifier.dense'							)

     return name

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     for key in orig_state_dict.copy().keys():
          lowercase_					:       List[str]     				=					orig_state_dict.pop(SCREAMING_SNAKE_CASE_							)

          if "qkv" in key:
               lowercase_					:       List[str]     				=					key.split('.'							)
               lowercase_					:       int     				=					int(key_split[3]							)
               lowercase_					:       Tuple     				=					config.hidden_size
               if "weight" in key:
                    lowercase_					:       Tuple     				=					val[:dim, :]
                    lowercase_					:       Union[str, Any]     				=					val[dim : dim * 2, :]
                    lowercase_					:       Optional[int]     				=					val[-dim:, :]
               else:
                    lowercase_					:       Optional[Any]     				=					val[:dim]
                    lowercase_					:       Any     				=					val[dim : dim * 2]
                    lowercase_					:       Tuple     				=					val[-dim:]
          else:
               lowercase_					:       Optional[Any]     				=					val

     return orig_state_dict

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       List[Any]     				=					[
         '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(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							)

@torch.no_grad()
def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_=False							):
     lowercase_					:       Dict     				=					get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE_							)

     lowercase_					:       Optional[int]     				=					{
         '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
     lowercase_					:       Dict     				=					model_name_to_url[model_name]
     lowercase_					:       Optional[Any]     				=					torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_  ,       map_location='cpu'							)
     # remove some keys
     remove_keys(SCREAMING_SNAKE_CASE_							)
     # rename some keys
     lowercase_					:       str     				=					convert_state_dict(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							)

     # load 🤗 model
     lowercase_					:       Optional[Any]     				=					ASTForAudioClassification(SCREAMING_SNAKE_CASE_							)
     model.eval()

     model.load_state_dict(SCREAMING_SNAKE_CASE_							)

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

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

          lowercase_				,lowercase_					:       Union[str, Any]     				=					torchaudio.load(SCREAMING_SNAKE_CASE_							)
          lowercase_					:       str     				=					waveform.squeeze().numpy()

     lowercase_					:       str     				=					feature_extractor(SCREAMING_SNAKE_CASE_  ,       sampling_rate=16_000  ,       return_tensors='pt'							)

     # forward pass
     lowercase_					:       Tuple     				=					model(**SCREAMING_SNAKE_CASE_							)
     lowercase_					:       Tuple     				=					outputs.logits

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

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

     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)




