



from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...utils import logging


if TYPE_CHECKING:
    from ...feature_extraction_utils import FeatureExtractionMixin
    from ...tokenization_utils_base import PreTrainedTokenizerBase
    from ...utils import TensorType

__UpperCAmelCase			  =			logging.get_logger(__name__)

__UpperCAmelCase			  =			{
    '''openai/whisper-base''': '''https://huggingface.co/openai/whisper-base/resolve/main/config.json''',
}

# fmt: off
__UpperCAmelCase			  =			[
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
    705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377,
    1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211,
    4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786,
    11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791,
    17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409,
    34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361
]
__UpperCAmelCase			  =			[
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
    893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627,
    3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647,
    7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793,
    14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675,
    22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865,
    42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362
]



class 							lowerCAmelCase_						(    a__				):
       UpperCAmelCase__							:   Dict  	=    "whisper"
       UpperCAmelCase__							:   int  	=    ["past_key_values"]
       UpperCAmelCase__							:   List[str]  	=    {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
       def __init__(     self,     SCREAMING_SNAKE_CASE_=5_1865,     SCREAMING_SNAKE_CASE_=80,     SCREAMING_SNAKE_CASE_=6,     SCREAMING_SNAKE_CASE_=4,     SCREAMING_SNAKE_CASE_=6,     SCREAMING_SNAKE_CASE_=4,     SCREAMING_SNAKE_CASE_=1536,     SCREAMING_SNAKE_CASE_=1536,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=5_0257,     SCREAMING_SNAKE_CASE_=True,     SCREAMING_SNAKE_CASE_=True,     SCREAMING_SNAKE_CASE_="gelu",     SCREAMING_SNAKE_CASE_=256,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=0.02,     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=1500,     SCREAMING_SNAKE_CASE_=448,     SCREAMING_SNAKE_CASE_=5_0256,     SCREAMING_SNAKE_CASE_=5_0256,     SCREAMING_SNAKE_CASE_=5_0256,     SCREAMING_SNAKE_CASE_=None,     SCREAMING_SNAKE_CASE_=[220, 5_0256],     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=256,     SCREAMING_SNAKE_CASE_=False,     SCREAMING_SNAKE_CASE_=0.05,     SCREAMING_SNAKE_CASE_=10,     SCREAMING_SNAKE_CASE_=2,     SCREAMING_SNAKE_CASE_=0.0,     SCREAMING_SNAKE_CASE_=10,     SCREAMING_SNAKE_CASE_=0,     SCREAMING_SNAKE_CASE_=7,     **SCREAMING_SNAKE_CASE_,     )	->						int:
          UpperCamelCase       :    List[str]		      =      vocab_size
          UpperCamelCase       :    Any		      =      num_mel_bins
          UpperCamelCase       :    Any		      =      d_model
          UpperCamelCase       :    List[Any]		      =      encoder_layers
          UpperCamelCase       :    Optional[int]		      =      encoder_attention_heads
          UpperCamelCase       :    Union[str, Any]		      =      decoder_layers
          UpperCamelCase       :    Any		      =      decoder_attention_heads
          UpperCamelCase       :    Optional[int]		      =      decoder_ffn_dim
          UpperCamelCase       :    int		      =      encoder_ffn_dim
          UpperCamelCase       :    Optional[int]		      =      dropout
          UpperCamelCase       :    int		      =      attention_dropout
          UpperCamelCase       :    Any		      =      activation_dropout
          UpperCamelCase       :    Union[str, Any]		      =      activation_function
          UpperCamelCase       :    Any		      =      init_std
          UpperCamelCase       :    List[Any]		      =      encoder_layerdrop
          UpperCamelCase       :    int		      =      decoder_layerdrop
          UpperCamelCase       :    Dict		      =      use_cache
          UpperCamelCase       :    Dict		      =      encoder_layers
          UpperCamelCase       :    List[Any]		      =      scale_embedding  # scale factor will be sqrt(d_model) if True
          UpperCamelCase       :    int		      =      max_source_positions
          UpperCamelCase       :    List[Any]		      =      max_target_positions

          # Audio Classification-specific parameters. Feel free to ignore for other classes.
          UpperCamelCase       :    Optional[Any]		      =      classifier_proj_size
          UpperCamelCase       :    List[str]		      =      use_weighted_layer_sum

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          UpperCamelCase       :    List[str]		      =      apply_spec_augment
          UpperCamelCase       :    Optional[int]		      =      mask_time_prob
          UpperCamelCase       :    Dict		      =      mask_time_length
          UpperCamelCase       :    str		      =      mask_time_min_masks
          UpperCamelCase       :    List[str]		      =      mask_feature_prob
          UpperCamelCase       :    Union[str, Any]		      =      mask_feature_length
          UpperCamelCase       :    int		      =      mask_feature_min_masks

          UpperCamelCase       :    int		      =      median_filter_width

          super().__init__(
              pad_token_id=SCREAMING_SNAKE_CASE_,     bos_token_id=SCREAMING_SNAKE_CASE_,     eos_token_id=SCREAMING_SNAKE_CASE_,     is_encoder_decoder=SCREAMING_SNAKE_CASE_,     decoder_start_token_id=SCREAMING_SNAKE_CASE_,     suppress_tokens=SCREAMING_SNAKE_CASE_,     begin_suppress_tokens=SCREAMING_SNAKE_CASE_,     **SCREAMING_SNAKE_CASE_,     )






class 							lowerCAmelCase_						(    a__				):
       @property
       def    snake_case_			(     self			)	->						Mapping[str, Mapping[int, str]]:
          UpperCamelCase       :    List[Any]		      =      OrderedDict(
              [
                  ('input_features', {0: 'batch', 1: 'feature_size', 2: 'encoder_sequence'}),
              ]			)
          if self.use_past:
             UpperCamelCase       :    Any		      =      {0: 'batch'}
          else:
             UpperCamelCase       :    Dict		      =      {0: 'batch', 1: 'decoder_sequence'}

          if self.use_past:
             self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE_,     direction='inputs'			)

          return common_inputs
       def    snake_case_			(     self,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_ = -1,     SCREAMING_SNAKE_CASE_ = -1,     SCREAMING_SNAKE_CASE_ = False,     SCREAMING_SNAKE_CASE_ = None,     SCREAMING_SNAKE_CASE_ = 2_2050,     SCREAMING_SNAKE_CASE_ = 5.0,     SCREAMING_SNAKE_CASE_ = 220,     )	->						Mapping[str, Any]:
          UpperCamelCase       :    Any		      =      OrderedDict()
          UpperCamelCase       :    str		      =      OnnxConfig.generate_dummy_inputs(
              self,     preprocessor=preprocessor.feature_extractor,     batch_size=SCREAMING_SNAKE_CASE_,     framework=SCREAMING_SNAKE_CASE_,     sampling_rate=SCREAMING_SNAKE_CASE_,     time_duration=SCREAMING_SNAKE_CASE_,     frequency=SCREAMING_SNAKE_CASE_,     )
          UpperCamelCase       :    Union[str, Any]		      =      encoder_inputs['input_features'].shape[2]
          UpperCamelCase       :    List[str]		      =      encoder_sequence_length // 2 if self.use_past else seq_length

          UpperCamelCase       :    Dict		      =      super().generate_dummy_inputs(
              preprocessor.tokenizer,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_,     SCREAMING_SNAKE_CASE_			)

          UpperCamelCase       :    Any		      =      encoder_inputs.pop('input_features'			)
          UpperCamelCase       :    Any		      =      decoder_inputs.pop('decoder_input_ids'			)

          if "past_key_values" in decoder_inputs:
             UpperCamelCase       :    Optional[int]		      =      decoder_inputs.pop('past_key_values'			)

          return dummy_inputs






       @property
       def    snake_case_			(     self			)	->						float:
          return 1e-3











'''simple docstring'''



import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
      import torch
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      '''char'''
      UpperCamelCase_             =      '''bpe'''
      UpperCamelCase_             =      '''wp'''





SCREAMING_SNAKE_CASE							=						(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class UpperCAmelCase_       (     __A					):




      """simple docstring"""




      UpperCamelCase_             =      ['''image_processor''', '''char_tokenizer''']
      UpperCamelCase_             =      '''ViTImageProcessor'''
      UpperCamelCase_             =      '''MgpstrTokenizer'''






      def __init__(			self      :		int  ,   UpperCAmelCase      :		Tuple=None  ,   UpperCAmelCase      :		Dict=None  ,   **UpperCAmelCase      :		Any		)	->	List[str]:


       '''simple docstring'''

       lowercase       : str						=None
       if "feature_extractor" in kwargs:
        warnings.warn(
            '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
            ''' instead.'''  ,   UpperCAmelCase  ,   )
        lowercase       : int						=kwargs.pop('''feature_extractor'''		)

       lowercase       : Optional[Any]						=image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
        raise ValueError('''You need to specify an `image_processor`.'''		)
       if tokenizer is None:
        raise ValueError('''You need to specify a `tokenizer`.'''		)

       lowercase       : Any						=tokenizer
       lowercase       : Dict						=AutoTokenizer.from_pretrained('''gpt2'''		)
       lowercase       : Optional[int]						=AutoTokenizer.from_pretrained('''bert-base-uncased'''		)

       super().__init__(UpperCAmelCase  ,   UpperCAmelCase		)






      def __call__(			self      :		List[Any]  ,   UpperCAmelCase      :		Union[str, Any]=None  ,   UpperCAmelCase      :		List[str]=None  ,   UpperCAmelCase      :		Dict=None  ,   **UpperCAmelCase      :		Union[str, Any]		)	->	int:


       '''simple docstring'''

       if images is None and text is None:
        raise ValueError('''You need to specify either an `images` or `text` input to process.'''		)

       if images is not None:
        lowercase       : str						=self.image_processor(UpperCAmelCase  ,   return_tensors=UpperCAmelCase  ,   **UpperCAmelCase		)
       if text is not None:
        lowercase       : Any						=self.char_tokenizer(UpperCAmelCase  ,   return_tensors=UpperCAmelCase  ,   **UpperCAmelCase		)

       if text is None:
        return inputs
       elif images is None:
        return encodings
       else:
        lowercase       : List[str]						=encodings['''input_ids''']
        return inputs






      def 					A__   (			self      :		List[Any]  ,   UpperCAmelCase      :		Optional[Any]		)	->	Optional[Any]:


       '''simple docstring'''

       lowercase	,		lowercase	,		lowercase       : Union[str, Any]						=sequences
       lowercase       : Dict						=char_preds.size(0		)

       lowercase	,		lowercase       : Any						=self._decode_helper(UpperCAmelCase  ,   '''char'''		)
       lowercase	,		lowercase       : int						=self._decode_helper(UpperCAmelCase  ,   '''bpe'''		)
       lowercase	,		lowercase       : Optional[Any]						=self._decode_helper(UpperCAmelCase  ,   '''wp'''		)

       lowercase       : Dict						=[]
       lowercase       : List[Any]						=[]
       for i in range(UpperCAmelCase		):
        lowercase       : List[str]						=[char_scores[i], bpe_scores[i], wp_scores[i]]
        lowercase       : Union[str, Any]						=[char_strs[i], bpe_strs[i], wp_strs[i]]
        lowercase       : List[str]						=scores.index(max(UpperCAmelCase		)		)
        final_strs.append(strs[max_score_index]		)
        final_scores.append(scores[max_score_index]		)

       lowercase       : List[Any]						={}
       lowercase       : Optional[Any]						=final_strs
       lowercase       : Optional[Any]						=final_scores
       lowercase       : str						=char_strs
       lowercase       : Tuple						=bpe_strs
       lowercase       : List[str]						=wp_strs
       return out






      def 					A__   (			self      :		str  ,   UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		Union[str, Any]		)	->	Optional[int]:


       '''simple docstring'''

       if format == DecodeType.CHARACTER:
        lowercase       : Union[str, Any]						=self.char_decode
        lowercase       : List[str]						=1
        lowercase       : Tuple						='''[s]'''
       elif format == DecodeType.BPE:
        lowercase       : Union[str, Any]						=self.bpe_decode
        lowercase       : Optional[int]						=2
        lowercase       : Optional[Any]						='''#'''
       elif format == DecodeType.WORDPIECE:
        lowercase       : List[str]						=self.wp_decode
        lowercase       : Union[str, Any]						=102
        lowercase       : int						='''[SEP]'''
       else:
        raise ValueError(f'Format {format} is not supported.'		)

       lowercase	,		lowercase       : Union[str, Any]						=[], []
       lowercase       : Optional[int]						=pred_logits.size(0		)
       lowercase       : List[str]						=pred_logits.size(1		)
       lowercase	,		lowercase       : Optional[int]						=pred_logits.topk(1  ,   dim=-1  ,   largest=UpperCAmelCase  ,   sorted=UpperCAmelCase		)
       lowercase       : Tuple						=preds_index.view(-1  ,   UpperCAmelCase		)[:, 1:]
       lowercase       : Any						=decoder(UpperCAmelCase		)
       lowercase	,		lowercase       : List[str]						=torch.nn.functional.softmax(UpperCAmelCase  ,   dim=2		).max(dim=2		)
       lowercase       : List[Any]						=preds_max_prob[:, 1:]

       for index in range(UpperCAmelCase		):
        lowercase       : List[Any]						=preds_str[index].find(UpperCAmelCase		)
        lowercase       : Any						=preds_str[index][:pred_eos]
        lowercase       : Any						=preds_index[index].cpu().tolist()
        lowercase       : Optional[int]						=pred_index.index(UpperCAmelCase		) if eos_token in pred_index else -1
        lowercase       : int						=preds_max_prob[index][: pred_eos_index + 1]
        lowercase       : Tuple						=pred_max_prob.cumprod(dim=0		)[-1] if pred_max_prob.nelement() != 0 else 0.0
        dec_strs.append(UpperCAmelCase		)
        conf_scores.append(UpperCAmelCase		)

       return dec_strs, conf_scores






      def 					A__   (			self      :		List[str]  ,   UpperCAmelCase      :		Optional[int]		)	->	Dict:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=[seq.replace(''' '''  ,   ''''''		) for seq in self.char_tokenizer.batch_decode(UpperCAmelCase		)]
       return decode_strs






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		Optional[Any]		)	->	str:


       '''simple docstring'''

       return self.bpe_tokenizer.batch_decode(UpperCAmelCase		)






      def 					A__   (			self      :		Tuple  ,   UpperCAmelCase      :		Dict		)	->	List[str]:


       '''simple docstring'''

       lowercase       : str						=[seq.replace(''' '''  ,   ''''''		) for seq in self.wp_tokenizer.batch_decode(UpperCAmelCase		)]
       return decode_strs



