





import shutil
import tempfile
import unittest

import pytest

from transformers import WhisperTokenizer, is_speech_available
from transformers.testing_utils import require_sentencepiece, require_torch, require_torchaudio

from .test_feature_extraction_whisper import floats_list


if is_speech_available():
					from transformers import WhisperFeatureExtractor, WhisperProcessor


UpperCAmelCase_												=   50358
UpperCAmelCase_												=   50362
@require_torch
@require_torchaudio
@require_sentencepiece
class 	UpperCamelCase_						(     unittest.TestCase    ):




					def 		lowerCAmelCase	(						self     )						->							List[str]:
										_snake_case													= 'openai/whisper-small.en'
										_snake_case													= tempfile.mkdtemp()




					def 		lowerCAmelCase	(						self ,  **lowerCAmelCase_     )						->							Optional[int]:
										return WhisperTokenizer.from_pretrained(self.checkpoint ,  **__SCREAMING_SNAKE_CASE     )




					def 		lowerCAmelCase	(						self ,  **lowerCAmelCase_     )						->							List[str]:
										return WhisperFeatureExtractor.from_pretrained(self.checkpoint ,  **__SCREAMING_SNAKE_CASE     )




					def 		lowerCAmelCase	(						self     )						->							List[str]:
										shutil.rmtree(self.tmpdirname     )




					def 		lowerCAmelCase	(						self     )						->							Optional[Any]:
										_snake_case													= self.get_tokenizer()
										_snake_case													= self.get_feature_extractor()

										_snake_case													= WhisperProcessor(tokenizer=__SCREAMING_SNAKE_CASE ,  feature_extractor=__SCREAMING_SNAKE_CASE     )

										processor.save_pretrained(self.tmpdirname     )
										_snake_case													= WhisperProcessor.from_pretrained(self.tmpdirname     )

										self.assertEqual(processor.tokenizer.get_vocab() ,  tokenizer.get_vocab()     )
										self.assertIsInstance(processor.tokenizer ,  __SCREAMING_SNAKE_CASE     )

										self.assertEqual(processor.feature_extractor.to_json_string() ,  feature_extractor.to_json_string()     )
										self.assertIsInstance(processor.feature_extractor ,  __SCREAMING_SNAKE_CASE     )




					def 		lowerCAmelCase	(						self     )						->							str:
										_snake_case													= WhisperProcessor(tokenizer=self.get_tokenizer() ,  feature_extractor=self.get_feature_extractor()     )
										processor.save_pretrained(self.tmpdirname     )

										_snake_case													= self.get_tokenizer(bos_token='(BOS)' ,  eos_token='(EOS)'     )
										_snake_case													= self.get_feature_extractor(do_normalize=__SCREAMING_SNAKE_CASE ,  padding_value=1.0     )

										_snake_case													= WhisperProcessor.from_pretrained(
										    self.tmpdirname ,  bos_token='(BOS)' ,  eos_token='(EOS)' ,  do_normalize=__SCREAMING_SNAKE_CASE ,  padding_value=1.0     )

										self.assertEqual(processor.tokenizer.get_vocab() ,  tokenizer_add_kwargs.get_vocab()     )
										self.assertIsInstance(processor.tokenizer ,  __SCREAMING_SNAKE_CASE     )

										self.assertEqual(processor.feature_extractor.to_json_string() ,  feature_extractor_add_kwargs.to_json_string()     )
										self.assertIsInstance(processor.feature_extractor ,  __SCREAMING_SNAKE_CASE     )




					def 		lowerCAmelCase	(						self     )						->							str:
										_snake_case													= self.get_feature_extractor()
										_snake_case													= self.get_tokenizer()

										_snake_case													= WhisperProcessor(tokenizer=__SCREAMING_SNAKE_CASE ,  feature_extractor=__SCREAMING_SNAKE_CASE     )

										_snake_case													= floats_list((3, 1000)     )

										_snake_case													= feature_extractor(__SCREAMING_SNAKE_CASE ,  return_tensors='np'     )
										_snake_case													= processor(__SCREAMING_SNAKE_CASE ,  return_tensors='np'     )

										for key in input_feat_extract.keys():
															self.assertAlmostEqual(input_feat_extract[key].sum() ,  input_processor[key].sum() ,  delta=1E-2     )




					def 		lowerCAmelCase	(						self     )						->							Optional[int]:
										_snake_case													= self.get_feature_extractor()
										_snake_case													= self.get_tokenizer()

										_snake_case													= WhisperProcessor(tokenizer=__SCREAMING_SNAKE_CASE ,  feature_extractor=__SCREAMING_SNAKE_CASE     )

										_snake_case													= 'This is a test string'

										_snake_case													= processor(text=__SCREAMING_SNAKE_CASE     )

										_snake_case													= tokenizer(__SCREAMING_SNAKE_CASE     )

										for key in encoded_tok.keys():
															self.assertListEqual(encoded_tok[key] ,  encoded_processor[key]     )




					def 		lowerCAmelCase	(						self     )						->							List[str]:
										_snake_case													= self.get_feature_extractor()
										_snake_case													= self.get_tokenizer()

										_snake_case													= WhisperProcessor(tokenizer=__SCREAMING_SNAKE_CASE ,  feature_extractor=__SCREAMING_SNAKE_CASE     )

										_snake_case													= [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

										_snake_case													= processor.batch_decode(__SCREAMING_SNAKE_CASE     )
										_snake_case													= tokenizer.batch_decode(__SCREAMING_SNAKE_CASE     )

										self.assertListEqual(__SCREAMING_SNAKE_CASE ,  __SCREAMING_SNAKE_CASE     )




					def 		lowerCAmelCase	(						self     )						->							int:
										_snake_case													= self.get_feature_extractor()
										_snake_case													= self.get_tokenizer()

										_snake_case													= WhisperProcessor(tokenizer=__SCREAMING_SNAKE_CASE ,  feature_extractor=__SCREAMING_SNAKE_CASE     )

										self.assertListEqual(
										    processor.model_input_names ,  feature_extractor.model_input_names ,  msg='`processor` and `feature_extractor` model input names do not match' ,  )




					def 		lowerCAmelCase	(						self     )						->							Dict:
										_snake_case													= self.get_feature_extractor()
										_snake_case													= self.get_tokenizer()

										_snake_case													= WhisperProcessor(tokenizer=__SCREAMING_SNAKE_CASE ,  feature_extractor=__SCREAMING_SNAKE_CASE     )
										_snake_case													= processor.get_decoder_prompt_ids(task='transcribe' ,  no_timestamps=__SCREAMING_SNAKE_CASE     )

										self.assertIsInstance(__SCREAMING_SNAKE_CASE ,  __SCREAMING_SNAKE_CASE     )
										for ids in forced_decoder_ids:
															self.assertIsInstance(__SCREAMING_SNAKE_CASE ,  (list, tuple)     )

										_snake_case													= [TRANSCRIBE, NOTIMESTAMPS]
										self.assertListEqual([ids[-1] for ids in forced_decoder_ids] ,  __SCREAMING_SNAKE_CASE     )




					def 		lowerCAmelCase	(						self     )						->							Optional[Any]:
										_snake_case													= WhisperProcessor(tokenizer=self.get_tokenizer() ,  feature_extractor=self.get_feature_extractor()     )
										_snake_case													= processor.get_prompt_ids('Mr. Quilter'     )
										_snake_case													= processor.tokenizer.decode(__SCREAMING_SNAKE_CASE     )

										self.assertListEqual(prompt_ids.tolist() ,  [5_0360, 1770, 13, 2264, 346, 353]     )
										self.assertEqual(__SCREAMING_SNAKE_CASE ,  '<|startofprev|> Mr. Quilter'     )




					def 		lowerCAmelCase	(						self     )						->							int:
										_snake_case													= WhisperProcessor(tokenizer=self.get_tokenizer() ,  feature_extractor=self.get_feature_extractor()     )
										_snake_case													= processor.get_prompt_ids(''     )
										_snake_case													= processor.tokenizer.decode(__SCREAMING_SNAKE_CASE     )

										self.assertListEqual(prompt_ids.tolist() ,  [5_0360, 220]     )
										self.assertEqual(__SCREAMING_SNAKE_CASE ,  '<|startofprev|> '     )






					def 		lowerCAmelCase	(						self     )						->							List[str]:
										_snake_case													= WhisperProcessor(tokenizer=self.get_tokenizer() ,  feature_extractor=self.get_feature_extractor()     )

										def _test_prompt_error_raised_helper(lowerCAmelCase_ ,  lowerCAmelCase_     ):
															with pytest.raises(__SCREAMING_SNAKE_CASE     ) as excinfo:
																				processor.get_prompt_ids(__SCREAMING_SNAKE_CASE     )
															_snake_case													= F'''Encountered text in the prompt corresponding to disallowed special token: {special_token}.'''
															self.assertEqual(__SCREAMING_SNAKE_CASE ,  str(excinfo.value     )     )

										_test_prompt_error_raised_helper('<|startofprev|> test' ,  '<|startofprev|>'     )
										_test_prompt_error_raised_helper('test <|notimestamps|>' ,  '<|notimestamps|>'     )
										_test_prompt_error_raised_helper('test <|zh|> test <|transcribe|>' ,  '<|zh|>'     )










"""simple docstring"""


import argparse
import json
import sys
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import List

import torch
import torch.nn as nn
from huggingface_hub import cached_download, hf_hub_download
from torch import Tensor

from transformers import AutoImageProcessor, VanConfig, VanForImageClassification
from transformers.models.deprecated.van.modeling_van import VanLayerScaling
from transformers.utils import logging


logging.set_verbosity_info()
a__    :   Any    						= logging.get_logger(__name__)



@dataclass
class    lowercase_ :
       snake_case__ :							nn.Module
       snake_case__ :							List[nn.Module] 							=   field(default_factory=__lowerCAmelCase							)
       snake_case__ :							list 							=   field(default_factory=__lowerCAmelCase							)

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= len(list(m.modules()   )   ) == 1 or isinstance(__SCREAMING_SNAKE_CASE      ,    nn.Convad   ) or isinstance(__SCREAMING_SNAKE_CASE      ,    nn.BatchNormad   )
        if has_not_submodules:
         if not isinstance(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):
          self.traced.append(__SCREAMING_SNAKE_CASE   )

       def __call__(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        for m in self.module.modules():
         self.handles.append(m.register_forward_hook(self._forward_hook   )   )
        self.module(__SCREAMING_SNAKE_CASE   )
        [x.remove() for x in self.handles]
        return self

       @property
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        return list(filter(lambda __SCREAMING_SNAKE_CASE   : len(list(x.state_dict().keys()   )   ) > 0      ,    self.traced   )   )



@dataclass
class    lowercase_ :
       snake_case__ :							nn.Module
       snake_case__ :							nn.Module
       snake_case__ :							int 							=   0
       snake_case__ :							List 							=   field(default_factory=__lowerCAmelCase							)
       snake_case__ :							List 							=   field(default_factory=__lowerCAmelCase							)

       def __call__(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= Tracker(self.dest   )(__SCREAMING_SNAKE_CASE   ).parametrized
        snake_case__										= Tracker(self.src   )(__SCREAMING_SNAKE_CASE   ).parametrized

        snake_case__										= list(filter(lambda __SCREAMING_SNAKE_CASE   : type(__SCREAMING_SNAKE_CASE   ) not in self.src_skip      ,    __SCREAMING_SNAKE_CASE   )   )
        snake_case__										= list(filter(lambda __SCREAMING_SNAKE_CASE   : type(__SCREAMING_SNAKE_CASE   ) not in self.dest_skip      ,    __SCREAMING_SNAKE_CASE   )   )

        if len(__SCREAMING_SNAKE_CASE   ) != len(__SCREAMING_SNAKE_CASE   ):
         raise Exception(
             F"Numbers of operations are different. Source module has {len(__SCREAMING_SNAKE_CASE   )} operations while"
             F" destination module has {len(__SCREAMING_SNAKE_CASE   )}."   )

        for dest_m, src_m in zip(__SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE   ):
         dest_m.load_state_dict(src_m.state_dict()   )
         if self.verbose == 1:
          print(F"Transfered from={src_m} to={dest_m}"   )





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		)			->     nn.Module:

 '''simple docstring'''






 snake_case__										= from_model.state_dict()
 snake_case__										= our_model.state_dict()
 snake_case__										= our_model.config
 snake_case__										= []
 for stage_idx in range(len(config.hidden_sizes		)		):
  for block_id in range(config.depths[stage_idx]		):
   snake_case__										= f"block{stage_idx + 1}.{block_id}.layer_scale_1"
   snake_case__										= f"van.encoder.stages.{stage_idx}.layers.{block_id}.attention_scaling.weight"

   all_keys.append((from_key, to_key)		)
   snake_case__										= f"block{stage_idx + 1}.{block_id}.layer_scale_2"
   snake_case__										= f"van.encoder.stages.{stage_idx}.layers.{block_id}.mlp_scaling.weight"

   all_keys.append((from_key, to_key)		)

 for from_key, to_key in all_keys:
  snake_case__										= from_state_dict.pop(_UpperCAmelCase		)

 our_model.load_state_dict(_UpperCAmelCase		)
 return our_model





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase = True		,   )			->     Union[str, Any]:

 '''simple docstring'''






 print(f"Downloading weights for {name}..."		)
 snake_case__										= cached_download(_UpperCAmelCase		)
 print(f"Converting {name}..."		)
 snake_case__										= torch.load(_UpperCAmelCase		)["state_dict"]
 from_model.load_state_dict(_UpperCAmelCase		)
 from_model.eval()
 with torch.no_grad():
  snake_case__										= VanForImageClassification(_UpperCAmelCase		).eval()
  snake_case__										= ModuleTransfer(src=_UpperCAmelCase		,   dest=_UpperCAmelCase		)
  snake_case__										= torch.randn((1, 3, 2_2_4, 2_2_4)		)
  module_transfer(_UpperCAmelCase		)
  snake_case__										= copy_parameters(_UpperCAmelCase		,   _UpperCAmelCase		)

 if not torch.allclose(from_model(_UpperCAmelCase		)		,   our_model(_UpperCAmelCase		).logits		):
  raise ValueError("The model logits don't match the original one."		)

 snake_case__										= name
 print(_UpperCAmelCase		)

 if push_to_hub:
  our_model.push_to_hub(
      repo_path_or_name=save_directory / checkpoint_name		,   commit_message="Add model"		,   use_temp_dir=_UpperCAmelCase		,   )

  # we can use the convnext one
  snake_case__										= AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k"		)
  image_processor.push_to_hub(
      repo_path_or_name=save_directory / checkpoint_name		,   commit_message="Add image processor"		,   use_temp_dir=_UpperCAmelCase		,   )

  print(f"Pushed {checkpoint_name}"		)





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase = None		,   _UpperCAmelCase = True		)			->     Union[str, Any]:

 '''simple docstring'''






 snake_case__										= "imagenet-1k-id2label.json"
 snake_case__										= 1_0_0_0

 snake_case__										= "huggingface/label-files"
 snake_case__										= num_labels
 snake_case__										= json.load(open(hf_hub_download(_UpperCAmelCase		,   _UpperCAmelCase		,   repo_type="dataset"		)		,   "r"		)		)
 snake_case__										= {int(_UpperCAmelCase		): v for k, v in idalabel.items()}

 snake_case__										= idalabel
 snake_case__										= {v: k for k, v in idalabel.items()}

 snake_case__										= partial(_UpperCAmelCase		,   num_labels=_UpperCAmelCase		,   idalabel=_UpperCAmelCase		,   labelaid=_UpperCAmelCase		)

 snake_case__										= {
     "van-tiny": ImageNetPreTrainedConfig(
         hidden_sizes=[3_2, 6_4, 1_6_0, 2_5_6]		,   depths=[3, 3, 5, 2]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
     "van-small": ImageNetPreTrainedConfig(
         hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]		,   depths=[2, 2, 4, 2]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
     "van-base": ImageNetPreTrainedConfig(
         hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]		,   depths=[3, 3, 1_2, 3]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
     "van-large": ImageNetPreTrainedConfig(
         hidden_sizes=[6_4, 1_2_8, 3_2_0, 5_1_2]		,   depths=[3, 5, 2_7, 3]		,   mlp_ratios=[8, 8, 4, 4]		,   ),
 }

 snake_case__										= {
     "van-tiny": van_tiny,
     "van-small": van_small,
     "van-base": van_base,
     "van-large": van_large,
 }

 snake_case__										= {
     "van-tiny": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Tiny-original/resolve/main/van_tiny_754.pth.tar"
     ),
     "van-small": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Small-original/resolve/main/van_small_811.pth.tar"
     ),
     "van-base": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Base-original/resolve/main/van_base_828.pth.tar"
     ),
     "van-large": (
         "https://huggingface.co/Visual-Attention-Network/VAN-Large-original/resolve/main/van_large_839.pth.tar"
     ),
 }

 if model_name:
  convert_weight_and_push(
      _UpperCAmelCase		,   names_to_config[model_name]		,   checkpoint=names_to_original_checkpoints[model_name]		,   from_model=names_to_original_models[model_name]()		,   save_directory=_UpperCAmelCase		,   push_to_hub=_UpperCAmelCase		,   )
 else:
  for model_name, config in names_to_config.items():
   convert_weight_and_push(
       _UpperCAmelCase		,   _UpperCAmelCase		,   checkpoint=names_to_original_checkpoints[model_name]		,   from_model=names_to_original_models[model_name]()		,   save_directory=_UpperCAmelCase		,   push_to_hub=_UpperCAmelCase		,   )


if __name__ == "__main__":
   a__    :   Any    						= argparse.ArgumentParser()
   # Required parameters
   parser.add_argument(
       """--model-name""",
       default=None,
       type=str,
       help=(
           """The name of the model you wish to convert, it must be one of the supported resnet* architecture,"""
           """ currently: van-tiny/small/base/large. If `None`, all of them will the converted."""
       ),
   )
   parser.add_argument(
       """--pytorch_dump_folder_path""",
       default=None,
       type=Path,
       required=True,
       help="""Path to the output PyTorch model directory.""",
   )
   parser.add_argument(
       """--van_dir""",
       required=True,
       type=Path,
       help=(
           """A path to VAN's original implementation directory. You can download from here:"""
           """ https://github.com/Visual-Attention-Network/VAN-Classification"""
       ),
   )
   parser.add_argument(
       """--push_to_hub""",
       default=True,
       type=bool,
       required=False,
       help="""If True, push model and image processor to the hub.""",
   )

   a__    :   Any    						= parser.parse_args()
   a__    :   Path    						= args.pytorch_dump_folder_path
   pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
   a__    :   int    						= args.van_dir
   # append the path to the parents to maskformer dir
   sys.path.append(str(van_dir.parent))
   from van.models.van import van_base, van_large, van_small, van_tiny

   convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)

