


'''simple docstring'''

import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


lowerCamelCase				:  str    		=      logging.get_logger(__name__)

lowerCamelCase				:  str    		=      {'vocab_file': 'spiece.model'}

lowerCamelCase				:  int    		=      {
    'vocab_file': {
        'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model',
    }
}
class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      def __init__(self       :       List[Any]  ,		UpperCamelCase       :       Optional[Any]  ,		UpperCamelCase       :       Any=False  ,		UpperCamelCase       :       Dict=True  ,		UpperCamelCase       :       int=False  ,		UpperCamelCase       :       Optional[Any]="<s>"  ,		UpperCamelCase       :       Union[str, Any]="</s>"  ,		UpperCamelCase       :       Optional[int]="<unk>"  ,		UpperCamelCase       :       List[Any]="<sep>"  ,		UpperCamelCase       :       Dict="<pad>"  ,		UpperCamelCase       :       int="<cls>"  ,		UpperCamelCase       :       int="<mask>"  ,		UpperCamelCase       :       str=["<eop>", "<eod>"]  ,		UpperCamelCase       :       Optional[Dict[str, Any]] = None  ,		**UpperCamelCase       :       Dict  ,		):

             '''simple docstring'''







             lowercase__      =					AddedToken(UpperCamelCase  ,		lstrip=UpperCamelCase  ,		rstrip=UpperCamelCase					) if isinstance(UpperCamelCase  ,		UpperCamelCase					) else mask_token

             lowercase__      =					{} if sp_model_kwargs is None else sp_model_kwargs

             super().__init__(
                 do_lower_case=UpperCamelCase  ,		remove_space=UpperCamelCase  ,		keep_accents=UpperCamelCase  ,		bos_token=UpperCamelCase  ,		eos_token=UpperCamelCase  ,		unk_token=UpperCamelCase  ,		sep_token=UpperCamelCase  ,		pad_token=UpperCamelCase  ,		cls_token=UpperCamelCase  ,		mask_token=UpperCamelCase  ,		additional_special_tokens=UpperCamelCase  ,		sp_model_kwargs=self.sp_model_kwargs  ,		**UpperCamelCase  ,		)

             lowercase__      =					3

             lowercase__      =					do_lower_case
             lowercase__      =					remove_space
             lowercase__      =					keep_accents
             lowercase__      =					vocab_file

             lowercase__      =					spm.SentencePieceProcessor(**self.sp_model_kwargs					)
             self.sp_model.Load(UpperCamelCase					)

             try:
                    import jieba
             except ModuleNotFoundError as error:
                    raise error.__class__(
                        '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. '''
                        '''See https://pypi.org/project/jieba/ for installation.'''					)
             lowercase__      =					jieba
             lowercase__      =					str.maketrans(''' \n'''  ,		'''\u2582\u2583'''					)



      @property
      # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size
      def  UpperCamelCase__						(self       :       List[str]					):

             '''simple docstring'''







             return len(self.sp_model					)



      def  UpperCamelCase__						(self       :       List[Any]					):

             '''simple docstring'''







             lowercase__      =					{self.convert_ids_to_tokens(UpperCamelCase					): i for i in range(self.vocab_size					)}
             vocab.update(self.added_tokens_encoder					)
             return vocab



      def __getstate__(self       :       Union[str, Any]					):

             '''simple docstring'''







             lowercase__      =					self.__dict__.copy()
             lowercase__      =					None
             return state



      def __setstate__(self       :       Dict  ,		UpperCamelCase       :       int					):

             '''simple docstring'''







             lowercase__      =					d

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

             lowercase__      =					spm.SentencePieceProcessor(**self.sp_model_kwargs					)
             self.sp_model.Load(self.vocab_file					)



      def  UpperCamelCase__						(self       :       Optional[int]  ,		UpperCamelCase       :       Dict					):

             '''simple docstring'''







             if self.remove_space:
                    lowercase__      =					''' '''.join(inputs.strip().split()					)
             else:
                    lowercase__      =					inputs
             lowercase__      =					outputs.replace('''``'''  ,		'''"'''					).replace('''\'\''''  ,		'''"'''					)

             if not self.keep_accents:
                    lowercase__      =					unicodedata.normalize('''NFKD'''  ,		UpperCamelCase					)
                    lowercase__      =					''''''.join([c for c in outputs if not unicodedata.combining(UpperCamelCase					)]					)
             if self.do_lower_case:
                    lowercase__      =					outputs.lower()

             return outputs



      def  UpperCamelCase__						(self       :       List[Any]  ,		UpperCamelCase       :       str					):

             '''simple docstring'''







             lowercase__      =					self.preprocess_text(UpperCamelCase					)
             lowercase__      =					self.sp_model.encode(UpperCamelCase  ,		out_type=UpperCamelCase					)
             lowercase__      =					[]
             for piece in pieces:
                    if len(UpperCamelCase					) > 1 and piece[-1] == str(''','''					) and piece[-2].isdigit():
                           lowercase__      =					self.sp_model.EncodeAsPieces(piece[:-1].replace(UpperCamelCase  ,		''''''					)					)
                           if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                                  if len(cur_pieces[0]					) == 1:
                                         lowercase__      =					cur_pieces[1:]
                                  else:
                                         lowercase__      =					cur_pieces[0][1:]
                           cur_pieces.append(piece[-1]					)
                           new_pieces.extend(UpperCamelCase					)
                    else:
                           new_pieces.append(UpperCamelCase					)

             return new_pieces



      def  UpperCamelCase__						(self       :       int  ,		UpperCamelCase       :       str					):

             '''simple docstring'''







             return self.sp_model.PieceToId(UpperCamelCase					)



      def  UpperCamelCase__						(self       :       str  ,		UpperCamelCase       :       Optional[Any]					):

             '''simple docstring'''







             return self.sp_model.IdToPiece(UpperCamelCase					)



      def  UpperCamelCase__						(self       :       Union[str, Any]  ,		UpperCamelCase       :       str					):

             '''simple docstring'''







             lowercase__      =					''''''.join(UpperCamelCase					).replace(UpperCamelCase  ,		''' '''					).strip()
             return out_string



      def  UpperCamelCase__						(self       :       Any  ,		UpperCamelCase       :       List[int]  ,		UpperCamelCase       :       Optional[List[int]] = None					):

             '''simple docstring'''







             lowercase__      =					[self.sep_token_id]
             lowercase__      =					[self.cls_token_id]
             if token_ids_a is None:
                    return token_ids_a + sep + cls
             return token_ids_a + sep + token_ids_a + sep + cls



      def  UpperCamelCase__						(self       :       Tuple  ,		UpperCamelCase       :       List[int]  ,		UpperCamelCase       :       Optional[List[int]] = None  ,		UpperCamelCase       :       bool = False					):

             '''simple docstring'''







             if already_has_special_tokens:
                    return super().get_special_tokens_mask(
                        token_ids_a=UpperCamelCase  ,		token_ids_a=UpperCamelCase  ,		already_has_special_tokens=UpperCamelCase					)

             if token_ids_a is not None:
                    return ([0] * len(UpperCamelCase					)) + [1] + ([0] * len(UpperCamelCase					)) + [1, 1]
             return ([0] * len(UpperCamelCase					)) + [1, 1]



      def  UpperCamelCase__						(self       :       str  ,		UpperCamelCase       :       List[int]  ,		UpperCamelCase       :       Optional[List[int]] = None					):

             '''simple docstring'''







             lowercase__      =					[self.sep_token_id]
             lowercase__      =					[2]

             if token_ids_a is None:
                    return len(token_ids_a + sep					) * [0] + cls_segment_id
             return len(token_ids_a + sep					) * [0] + len(token_ids_a + sep					) * [1] + cls_segment_id



      def  UpperCamelCase__						(self       :       Tuple  ,		UpperCamelCase       :       str  ,		UpperCamelCase       :       Optional[str] = None					):

             '''simple docstring'''







             if not os.path.isdir(UpperCamelCase					):
                    logger.error(f"Vocabulary path ({save_directory}) should be a directory"					)
                    return
             lowercase__      =					os.path.join(
                 UpperCamelCase  ,		(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']					)

             if os.path.abspath(self.vocab_file					) != os.path.abspath(UpperCamelCase					) and os.path.isfile(self.vocab_file					):
                    copyfile(self.vocab_file  ,		UpperCamelCase					)
             elif not os.path.isfile(self.vocab_file					):
                    with open(UpperCamelCase  ,		'''wb'''					) as fi:
                           lowercase__      =					self.sp_model.serialized_model_proto()
                           fi.write(UpperCamelCase					)

             return (out_vocab_file,)






      def  UpperCamelCase__						(self       :       List[str]  ,		*UpperCamelCase       :       List[Any]  ,		**UpperCamelCase       :       Union[str, Any]					):

             '''simple docstring'''







             lowercase__      =					super()._decode(*UpperCamelCase  ,		**UpperCamelCase					)
             lowercase__      =					text.replace(''' '''  ,		''''''					).replace('''\u2582'''  ,		''' '''					).replace('''\u2583'''  ,		'''\n'''					)
             return text








'''simple docstring'''

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

lowerCamelCase				:  Dict    		=      logging.get_logger(__name__)

lowerCamelCase				:  List[Any]    		=      {
    'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json',
}

# fmt: off
lowerCamelCase				:  Dict    		=      [
    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
]
lowerCamelCase				:  str    		=      [
    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		(lowercase_	):





      '''simple docstring'''






      lowerCAmelCase__   :	List[str]       =				"""whisper"""
      lowerCAmelCase__   :	Dict       =				["""past_key_values"""]
      lowerCAmelCase__   :	Optional[int]       =				{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}



      def __init__(self       :       int  ,		UpperCamelCase       :       Optional[int]=51865  ,		UpperCamelCase       :       Any=80  ,		UpperCamelCase       :       Dict=6  ,		UpperCamelCase       :       str=4  ,		UpperCamelCase       :       Optional[Any]=6  ,		UpperCamelCase       :       List[Any]=4  ,		UpperCamelCase       :       Tuple=1536  ,		UpperCamelCase       :       Dict=1536  ,		UpperCamelCase       :       Any=0.0  ,		UpperCamelCase       :       Any=0.0  ,		UpperCamelCase       :       int=50257  ,		UpperCamelCase       :       List[str]=True  ,		UpperCamelCase       :       List[Any]=True  ,		UpperCamelCase       :       List[str]="gelu"  ,		UpperCamelCase       :       Dict=256  ,		UpperCamelCase       :       Optional[int]=0.0  ,		UpperCamelCase       :       str=0.0  ,		UpperCamelCase       :       str=0.0  ,		UpperCamelCase       :       Dict=0.02  ,		UpperCamelCase       :       List[Any]=False  ,		UpperCamelCase       :       int=1500  ,		UpperCamelCase       :       List[str]=448  ,		UpperCamelCase       :       int=50256  ,		UpperCamelCase       :       Optional[int]=50256  ,		UpperCamelCase       :       Optional[Any]=50256  ,		UpperCamelCase       :       Any=None  ,		UpperCamelCase       :       Tuple=[220, 50256]  ,		UpperCamelCase       :       Optional[Any]=False  ,		UpperCamelCase       :       int=256  ,		UpperCamelCase       :       Optional[int]=False  ,		UpperCamelCase       :       int=0.05  ,		UpperCamelCase       :       List[Any]=10  ,		UpperCamelCase       :       Optional[int]=2  ,		UpperCamelCase       :       Optional[int]=0.0  ,		UpperCamelCase       :       Dict=10  ,		UpperCamelCase       :       Union[str, Any]=0  ,		UpperCamelCase       :       Union[str, Any]=7  ,		**UpperCamelCase       :       Union[str, Any]  ,		):

             '''simple docstring'''







             lowercase__      =					vocab_size
             lowercase__      =					num_mel_bins
             lowercase__      =					d_model
             lowercase__      =					encoder_layers
             lowercase__      =					encoder_attention_heads
             lowercase__      =					decoder_layers
             lowercase__      =					decoder_attention_heads
             lowercase__      =					decoder_ffn_dim
             lowercase__      =					encoder_ffn_dim
             lowercase__      =					dropout
             lowercase__      =					attention_dropout
             lowercase__      =					activation_dropout
             lowercase__      =					activation_function
             lowercase__      =					init_std
             lowercase__      =					encoder_layerdrop
             lowercase__      =					decoder_layerdrop
             lowercase__      =					use_cache
             lowercase__      =					encoder_layers
             lowercase__      =					scale_embedding  # scale factor will be sqrt(d_model) if True
             lowercase__      =					max_source_positions
             lowercase__      =					max_target_positions

             # Audio Classification-specific parameters. Feel free to ignore for other classes.
             lowercase__      =					classifier_proj_size
             lowercase__      =					use_weighted_layer_sum

             # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
             lowercase__      =					apply_spec_augment
             lowercase__      =					mask_time_prob
             lowercase__      =					mask_time_length
             lowercase__      =					mask_time_min_masks
             lowercase__      =					mask_feature_prob
             lowercase__      =					mask_feature_length
             lowercase__      =					mask_feature_min_masks

             lowercase__      =					median_filter_width

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






class     __lowerCAmelCase		(lowercase_	):





      '''simple docstring'''






      @property
      def  UpperCamelCase__						(self       :       str					):

             '''simple docstring'''







             lowercase__      =					OrderedDict(
                 [
                     ('''input_features''', {0: '''batch''', 1: '''feature_size''', 2: '''encoder_sequence'''}),
                 ]					)
             if self.use_past:
                    lowercase__      =					{0: '''batch'''}
             else:
                    lowercase__      =					{0: '''batch''', 1: '''decoder_sequence'''}

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

             return common_inputs



      def  UpperCamelCase__						(self       :       Union[str, Any]  ,		UpperCamelCase       :       Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]  ,		UpperCamelCase       :       int = -1  ,		UpperCamelCase       :       int = -1  ,		UpperCamelCase       :       bool = False  ,		UpperCamelCase       :       Optional["TensorType"] = None  ,		UpperCamelCase       :       int = 22050  ,		UpperCamelCase       :       float = 5.0  ,		UpperCamelCase       :       int = 220  ,		):

             '''simple docstring'''







             lowercase__      =					OrderedDict()
             lowercase__      =					OnnxConfig.generate_dummy_inputs(
                 self  ,		preprocessor=preprocessor.feature_extractor  ,		batch_size=UpperCamelCase  ,		framework=UpperCamelCase  ,		sampling_rate=UpperCamelCase  ,		time_duration=UpperCamelCase  ,		frequency=UpperCamelCase  ,		)
             lowercase__      =					encoder_inputs['''input_features'''].shape[2]
             lowercase__      =					encoder_sequence_length // 2 if self.use_past else seq_length

             lowercase__      =					super().generate_dummy_inputs(
                 preprocessor.tokenizer  ,		UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase  ,		UpperCamelCase					)

             lowercase__      =					encoder_inputs.pop('''input_features'''					)
             lowercase__      =					decoder_inputs.pop('''decoder_input_ids'''					)

             if "past_key_values" in decoder_inputs:
                    lowercase__      =					decoder_inputs.pop('''past_key_values'''					)

             return dummy_inputs






      @property
      def  UpperCamelCase__						(self       :       Union[str, Any]					):

             '''simple docstring'''







             return 1E-3




