o
    h                     @   s  d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
ZddlZddlmZmZ ddlmZ dd	lmZmZ d
ddddZddiddiddidZddiZdd ZeeZdd Zi dddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:i d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\i d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~i ddddddddddddddddddddddddddddddddddi ddddddddddddddddddddddddddddddddddddddddddddddddddҜZi ddԄ e D dd/d1dddddKdKddddלZ ddgZ!G ddۄ deZ"dd݄ Z#ddd߄Z$dd Z%			ddee& de'de'de'fddZ(dee& fddZ)dee& fddZ*dd Z+dS )z!Tokenization classes for Whisper.    N)	lru_cache)ListOptionalTupleUnion   )
AddedTokenPreTrainedTokenizer)logging   )BasicTextNormalizerEnglishTextNormalizerz
vocab.jsonztokenizer.jsonz
merges.txtznormalizer.json)
vocab_filetokenizer_filemerges_filenormalizer_filezopenai/whisper-basezBhttps://huggingface.co/openai/whisper-base/resolve/main/vocab.jsonzGhttps://huggingface.co/openai/whisper-base/resolve/main/merges_file.txtzGhttps://huggingface.co/openai/whisper-base/resolve/main/normalizer.json)r   r   r   i  c                  C   s   t ttdtdd t ttdtdd  t ttdtdd  } | dd }d	}td
D ]}|| vrI| | |d
|  |d7 }q3dd |D }tt| |S )a8  
    Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
    characters the bpe code barfs on.

    The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
    if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
    decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
    tables between utf-8 bytes and unicode strings.
    !~r      ¡   ¬   ®   ÿNr      c                 S   s   g | ]}t |qS  )chr).0nr   r   f/var/www/html/ai/venv/lib/python3.10/site-packages/transformers/models/whisper/tokenization_whisper.py
<listcomp>H       z$bytes_to_unicode.<locals>.<listcomp>)listrangeordappenddictzip)bscsr   br   r   r   bytes_to_unicode4   s   L
r)   c                 C   s6   t  }| d }| dd D ]}|||f |}q|S )z
    Return set of symbol pairs in a word.

    Word is represented as tuple of symbols (symbols being variable-length strings).
    r   r   N)setadd)wordpairs	prev_charcharr   r   r   	get_pairsP   s   r0   enenglishzhchinesedegermanesspanishrurussiankokoreanfrfrenchjajapanesept
portuguesetrturkishplpolishcacatalannldutchararabicsvswedishititalianid
indonesianhihindififinnishvi
vietnamesehehebrewuk	ukrainianelgreekmsmalayr'   czechroromaniandadanishhu	hungariantatamilno	norwegianththaiururduhrcroatianbg	bulgarianlt
lithuanianlalatinmimaoriml	malayalamcywelshskslovaktetelugufapersianlvlatvianbnbengalisrserbianazazerbaijanisl	slovenianknkannadaetestonianmk
macedonianbrbretoneubasqueis	icelandichyarmeniannenepalimn	mongolianr&   bosniankkkazakhsqalbanianswswahiliglgalicianmrmarathipapunjabisisinhalakmkhmersnshonayoyorubasosomaliaf	afrikaansococcitankageorgianbe
belarusiantgtajiksdsindhigugujaratiamamharicyiyiddishlolaouzuzbekfofaroesehtzhaitian creolepspashtotkturkmennnnynorskmtmaltesesanskritluxembourgishmyanmartibetantagalogmalagasyassamesetatarhawaiianlingalahausabashkirjavanese	sundanese	cantonese)salbmybotlmgastthawlnhabajwsuyuec                 C      i | ]\}}||qS r   r   )r   codelanguager   r   r   
<dictcomp>       r   r   r   )burmese	valencianflemishhaitianletzeburgeschpushtopanjabi	moldavianmoldovan	sinhalese	castilianmandarin	translate
transcribec                       sD  e Zd ZdZeZeZeZ	ddgZ
										dW fdd		Zed
efddZdd Zdd ZdXdededefddZed
ee fddZdYd
ee fddZ	dZdee deee  ded
ee f fddZdd  Zd!d" Zd#d$ Zd%d& Zed[d'd(Zd\d
efd*d+Zd]d,d-Z e!d]d.d/Z"d[d0efd1d2Z#d3d4 Z$				)				d^d0ed5ed6ed7ed8ed9ed:ed
ef fd;d<Z%				d_d=e&eee f d0ed8ed9ed:ed
efd>d?Z'd@dA Z(dYdBedCee d
e)e fdDdEZ*d[dFdGZ+edHdI Z,d`dKdLZ-dMdN Z.dadPefdQdRZ/ed=ee dSedTefdUdVZ0  Z1S )bWhisperTokenizeraa	  
    Construct a Whisper tokenizer.

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
    the superclass for more information regarding such methods.

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Path to the merges file.
        normalizer_file (`str`, *optional*):
            Path to the normalizer_file file.
        errors (`str`, *optional*, defaults to `"replace"`):
            Paradigm to follow when decoding bytes to UTF-8. See
            [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
        unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The beginning of sequence token. The `decoder_start_token_id` is used to set the first token as
            `"<|startoftranscript|>"` when generating.
        eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
            The end of sequence token.
        pad_token (`str`, *optional*):
            The token used for padding, for example when batching sequences of different lengths.
        add_prefix_space (`bool`, *optional*, defaults to `False`):
            Whether or not to add an initial space to the input. This allows to treat the leading word just as any
            other word.
        language (`str`, *optional*):
            The language of the transcription text. The corresponding language id token is appended to the start of the
            sequence for multilingual speech recognition and speech translation tasks, e.g. for Spanish the token
            `"<|es|>"` is appended to the start of sequence. This should be used for multilingual fine-tuning only.
        task (`str`, *optional*):
            Task identifier to append at the start of sequence (if any). This should be used for mulitlingual
            fine-tuning, with `"transcribe"` for speech recognition and `"translate"` for speech translation.
        predict_timestamps (`bool`, *optional*, defaults to `False`):
            Whether to omit the `<|notimestamps|>` token at the start of the sequence.
    	input_idsattention_maskNreplace<|endoftext|>Fc              	      s  t |trt|dddddn|}t |trt|dddddn|}t |tr.t|dddddn|}t |tr>t|dddddn|}t|dd}t|| _W d    n1 sWw   Y  dd | j D | _|| _	t
 | _dd | j D | _t|dd}| d	d
d }W d    n1 sw   Y  dd |D }tt|tt|| _i | _|	| _|d urt|dd}t|| _W d    n1 sw   Y  nd | _td| _td| _|
| _t jd||||||	d| || _|| _d S )NFT)lstriprstrip
normalizedspecialutf-8encodingc                 S   r   r   r   r   kvr   r   r   r   .  r   z-WhisperTokenizer.__init__.<locals>.<dictcomp>c                 S   r   r   r   r  r   r   r   r   1  r   
r   c                 S   s   g | ]}t | qS r   )tuplesplit)r   merger   r   r   r   4      z-WhisperTokenizer.__init__.<locals>.<listcomp>zJ's|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+z<\|(\d+\.\d+)\|>)errors	unk_token	bos_token	eos_token	pad_tokenadd_prefix_spacer   ) 
isinstancestrr   openjsonloadencoderitemsdecoderr  r)   byte_encoderbyte_decoderreadr  r$   r%   r!   len	bpe_rankscacher#  english_spelling_normalizerrecompilepattimestamp_patr   super__init__taskpredict_timestamps)selfr   r   r   r  r  r   r!  r"  r#  r   r9  r:  kwargsvocab_handlemerges_handle
bpe_merges	__class__r   r   r8    sf   

zWhisperTokenizer.__init__returnc                 C   s
   t | jS N)r/  r)  r;  r   r   r   
vocab_sizeQ  s   
zWhisperTokenizer.vocab_sizec                    s(    fddt  jD }| j |S )Nc                    s   i | ]}  ||qS r   )convert_ids_to_tokensr   irD  r   r   r   V  r  z.WhisperTokenizer.get_vocab.<locals>.<dictcomp>)r!   rE  updateadded_tokens_encoder)r;  vocabr   rD  r   	get_vocabU  s   zWhisperTokenizer.get_vocabc           
         sX  | j v r
 j | S t|}t|}|s|S 	 t| fddd}| jvr'ny|\}}g }d}|t|k rz|||}	W n tyO   |||d   Y n?w ||||	  |	}|| |kr}|t|d k r}||d  |kr}|	||  |d7 }n|	||  |d7 }|t|k s5t|}|}t|dkrnt|}qd
|}| j |< |S )	NTc                    s    j | tdS )Ninf)r0  getfloat)pairrD  r   r   <lambda>e  s    z&WhisperTokenizer.bpe.<locals>.<lambda>keyr   r       )r1  r  r0   minr0  r/  index
ValueErrorextendr#   join)
r;  tokenr,   r-   bigramfirstsecondnew_wordrH  jr   rD  r   bpe[  sJ   


,


zWhisperTokenizer.bper   r9  r:  c                 C   sF   |dur|n| j | _ |dur|n| j| _|dur|| _dS | j| _dS )a  
        Override the prefix tokens appended to the start of the label sequence. This method can be used standalone to
        update the prefix tokens as required when fine-tuning. Example:

        ```python
        >>> # instantiate the tokenizer and set the prefix token to Spanish
        >>> tokenizer = WhisperTokenizer.from_pretrained("openai/whisper-tiny", language="spanish")
        >>> # now switch the prefix token from Spanish to French
        >>> tokenizer.set_prefix_tokens(language="french")
        ```

        Args:
            language (`str`, *optional*, defaults to `None`):
                The language of the transcription text.
            task (`str`, *optional*, defaults to `None`):
                Task identifier to append at the start of sequence (if any).
            predict_timestamps (`bool`, *optional*, defaults to `None`):
                Whether to omit the `<|notimestamps|>` token at the start of the sequence.
        N)r   r9  r:  )r;  r   r9  r:  r   r   r   set_prefix_tokens  s   z"WhisperTokenizer.set_prefix_tokensc           	      C   s<  |  d}|  d}|  d}|  d}tt }| jd urZ| j | _| jtv r0t| j }n*| jt v r;| j}nt| jdk}t	d| j d|rPt
t nt
t  d| jd uro| jtvrot	d	| j d
t |g}| jd ur||d ||  | jd ur|| jdkr|n| | js|| |S )N<|startoftranscript|>z<|translate|>z<|transcribe|><|notimestamps|>rT  zUnsupported language: z. Language should be one of: .zUnsupported task: z. Task should be in: r   r  )convert_tokens_to_idsr  	LANGUAGESkeysr   lowerTO_LANGUAGE_CODEvaluesr/  rX  r    r9  TASK_IDSr#   rW  r:  )	r;  bos_token_idtranslate_token_idtranscribe_token_idnotimestamps_token_idlangslanguage_idis_language_codebos_sequencer   r   r   prefix_tokens  s8   











zWhisperTokenizer.prefix_tokensc                 C   s0   |du r| j | | jg S | j | | | jg S )z=Build model inputs from a sequence by appending eos_token_id.N)ru  eos_token_id)r;  token_ids_0token_ids_1r   r   r    build_inputs_with_special_tokens  s   z1WhisperTokenizer.build_inputs_with_special_tokensrw  rx  already_has_special_tokensc                    sn   |rt  j||ddS dgt| j }dg}|du r%|dgt|  | S |dgt|  dgt|  | S )a  
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        T)rw  rx  rz  r   Nr   )r7  get_special_tokens_maskr/  ru  )r;  rw  rx  rz  prefix_onessuffix_onesr@  r   r   r{    s   $z(WhisperTokenizer.get_special_tokens_maskc                    sZ   g }t  j|D ]!}d fdd|dD }|dd  |dD  q	|S )zTokenize a string. c                 3   s    | ]} j | V  qd S rC  )r,  )r   r(   rD  r   r   	<genexpr>  s    

z-WhisperTokenizer._tokenize.<locals>.<genexpr>r  c                 s       | ]}|V  qd S rC  r   )r   	bpe_tokenr   r   r   r        rU  )r3  findallr5  rZ  encoderY  ra  r  )r;  text
bpe_tokensr[  r   rD  r   	_tokenize  s   "zWhisperTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r)  rN  r  )r;  r[  r   r   r   _convert_token_to_id  s   z%WhisperTokenizer._convert_token_to_idc                 C   s   | j |dS )z
        Converts an index (integer) in a token (str) using the vocab. Whisper's base tokenizer always decodes OOV
        tokens as "", thus we do not use the `unk_token` here.
        r~  )r+  rN  )r;  rW  r   r   r   _convert_id_to_token  s   z%WhisperTokenizer._convert_id_to_tokenc                 C   s   t | j}||S )z
        Normalize a given string using the `EnglishTextNormalizer` class, which preforms commons transformation on
        english text.
        )r   r2  )r;  r  
normalizerr   r   r   
_normalize  s   
zWhisperTokenizer._normalizec                 C   s   t |d}|| S )z
        Normalize a given string using the `BasicTextNormalizer` class, which preforms commons transformation on
        multilingual text.
        remove_diacritics)r   )r  r  r  r   r   r   _basic_normalize  s   
z!WhisperTokenizer._basic_normalize{Gz?c                    s~    j d d }g g}|D ]#}||kr(d|| | dd}|| |g  q|d | q fdd|D }d|S )	z
        Timestamp tokens are above the special tokens' id range and are ignored by `decode()`. This method decodes
        given tokens with timestamps tokens annotated, e.g. "<|1.08|>".
        r  r   z<|z.2fz|>c                    s(   g | ]}t |tr|n j|d qS )skip_special_tokens)r$  r%  decode)r   sr;  r  r   r   r     s    z<WhisperTokenizer._decode_with_timestamps.<locals>.<listcomp>r~  )all_special_idsr#   rZ  )r;  	token_idsr  time_precisiontimestamp_beginoutputsr[  	timestampr   r  r   _decode_with_timestamps  s   

z(WhisperTokenizer._decode_with_timestampsc                 C   sZ  g }t |}|jd dkrt|jdkrtd| jd d }||k}t |dd |dd @ d d }|jd dkrF| dkrFg S t |d d d |vrbt |t |d d d }t |d d }|D ]=}||| }	t|	dkr|	d 	 | }
|	d 	 | }| 
|	}	| |	}| |}|||
| || fd |}qm|S )a~  
        Compute offsets for a given tokenized input

        Args:
            token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
                List of tokenized input ids. Can be obtained using the `__call__` method.
            time_precision (`float`, `optional`, defaults to 0.02):
                The time ratio to convert from token to time.
        r   r   z)Can only process a single input at a timer  Nr  r  )nparrayshaper/  rX  r  wheresumr#   item_preprocess_token_ids_decode_filter_timestamp_ids)r;  r  r  offsetsr  timestamp_tokensconsecutive
last_slicecurrent_slicesliced_tokensstart_timestamp_positionend_timestamp_positionr  r   r   r   _compute_offsets!  s:   

&


	z!WhisperTokenizer._compute_offsetsc                    s   |   fddtdD S )a  
        Compute the timestamp token ids for a given precision and save to least-recently used (LRU) cache.

        Args:
            time_precision (`float`, `optional`, defaults to 0.02):
                The time ratio to convert from token to time.
        c                    s   g | ]}d |   qS )z<|%.2f|>r   rG  r  r   r   r   Z  r  z2WhisperTokenizer.timestamp_ids.<locals>.<listcomp>i  )rf  r!   )r;  r  r   r  r   timestamp_idsQ  s   	zWhisperTokenizer.timestamp_idsr  c                 C   s*   |r|  d}|  d}| |||}|S )a  
        Pre-process the token ids for decoding by removing the prompt tokens ids and timestamp token ids.

        Args:
            token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
                List of tokenized input ids. Typically, obtained using the `__call__` method of the tokenizer.
            skip_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not to remove special tokens from the token ids. If `True`, the prompt token ids will be
                removed.
        <|startofprev|>rc  )rf  _strip_prompt)r;  r  r  prompt_token_iddecoder_start_token_idr   r   r   r  \  s
   

z&WhisperTokenizer._preprocess_token_idsc                 C   s   t | jd|S )Nr~  )r3  subr6  )r;  r  r   r   r   r  n     z&WhisperTokenizer._filter_timestamp_idsclean_up_tokenization_spacesoutput_offsetsdecode_with_timestamps	normalizebasic_normalizer  c
                    sn   | j ||d}t j|f|||||	d|
}|r"| j|||d}n| |}|r5| j||d}||dS |S )a#	  
        Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
        tokens and clean up tokenization spaces.

        Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.

        Args:
            token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
                List of tokenized input ids. Can be obtained using the `__call__` method.
            skip_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not to remove special tokens in the decoding.
            clean_up_tokenization_spaces (`bool`, *optional*):
                Whether or not to clean up the tokenization spaces. If `None`, will default to
                `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
            output_offsets (`bool`, *optional*, defaults to `False`):
                Whether or not to output the offsets of the tokens. This should only be set if the model predicted
                timestamps.
            time_precision (`float`, `optional`, defaults to 0.02):
                The time ratio to convert from token to time.
            decode_with_timestamps (`bool`, *optional*, defaults to `False`):
                Whether or not to decode with timestamps included in the raw text.
            normalize (`bool`, *optional*, defaults to `False`):
                Whether or not to apply the English text normalizer to the decoded text. Only applicable when the
                target text is in English. Otherwise, the basic text normalizer should be applied.
            basic_normalize (`bool`, *optional*, defaults to `False`):
                Whether or not to apply the Basic text normalizer to the decoded text. Applicable to multilingual
                target text.
            remove_diacritics (`bool`, *optional*, defaults to `False`):
                Whether or not to remove diacritics when applying the Basic text normalizer. Removing diacritics may
                destroy information in the decoded text, hence it should be used with caution.
            kwargs (additional keyword arguments, *optional*):
                Will be passed to the underlying model specific decode method.
        Returns:
            `str`: The decoded sentence.
        r  )r  r  r  r  r  )r  r  r  )r  r  )r  r7  r  r  r  r  )r;  r  r  r  r  r  r  r  r  r  r<  filtered_idsr  r  r@  r   r   r  q  s0   0	

zWhisperTokenizer.decoder  c                 K   s   | dd| _| j||d}g }g }	|D ]&}
|r|
| jv rq|
| jv r5|	r/|| |	 g }	||
 q|	|
 q|	rE|| |	 d|}|rS| |}|S |r^| j	||d}|S |S )Nuse_source_tokenizerFr  r~  r  )
pop_decode_use_source_tokenizerrF  r  rJ  r#   convert_tokens_to_stringrZ  r  r  )r;  r  r  r  r  r  r<  filtered_tokens	sub_textscurrent_sub_textr[  r  
clean_textr   r   r   r    s.   	


zWhisperTokenizer._decodec                    s0   d |}t fdd|D jd jd}|S )z:Converts a sequence of tokens (string) in a single string.r~  c                    s   g | ]} j | qS r   )r-  )r   crD  r   r   r     r   z=WhisperTokenizer.convert_tokens_to_string.<locals>.<listcomp>r  )r  )rZ  	bytearrayr  r  )r;  tokensr  r   rD  r   r    s   
"z)WhisperTokenizer.convert_tokens_to_stringsave_directoryfilename_prefixc              	   C   s  t j|std| d d S t j||r|d ndtd  }t j||r,|d ndtd  }t j||r=|d ndtd  }t|dd	d
}|t	j
| jddddd  W d    n1 sew   Y  d}t|dd	d
:}|d t| j dd dD ]!\}	}
||
krtd| d |
}|d|	d  |d7 }qW d    n1 sw   Y  | jd urt|dd	d
}|t	j
| jddddd  W d    n1 sw   Y  |||fS )NzVocabulary path (z) should be a directory-r~  r   r   r   wr  r  rT  TF)indent	sort_keysensure_asciir  r   z#version: 0.2
c                 S   s   | d S )Nr   r   )kvr   r   r   rQ    s    z2WhisperTokenizer.save_vocabulary.<locals>.<lambda>rR  zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!rU  r   )ospathisdirloggererrorrZ  VOCAB_FILES_NAMESr&  writer'  dumpsr)  sortedr0  r*  warningr2  )r;  r  r  r   
merge_filer   frW  writerr  token_indexr   r   r   save_vocabulary  sF    




z WhisperTokenizer.save_vocabularyc                 K   s&   | d| j}|s|rd| }||fS )Nr#  rU  )r  r#  )r;  r  is_split_into_wordsr<  r#  r   r   r   prepare_for_tokenization  s   z)WhisperTokenizer.prepare_for_tokenizationc                 C   s   t d| jj d dS )zv
        A simple chat template that ignores role information and just concatenates messages with EOS tokens.
        zU
No chat template is defined for this tokenizer - using the default template for the z class. If the default is not appropriate for your model, please set `tokenizer.chat_template` to an appropriate template. See https://huggingface.co/docs/transformers/main/chat_templating for more information.
zM{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %})r  warning_oncerA  __name__rD  r   r   r   default_chat_template  s   z&WhisperTokenizer.default_chat_templateTc                 C   s6   | j ||| d | jdd  }dd t|D }|S )N)r9  r   r:  r   c                 S   s   g | ]
\}}|d  |fqS )r   r   )r   rankr[  r   r   r   r   /  s    z;WhisperTokenizer.get_decoder_prompt_ids.<locals>.<listcomp>)rb  ru  	enumerate)r;  r9  r   no_timestampsforced_tokensforced_decoder_idsr   r   r   get_decoder_prompt_ids(  s   z'WhisperTokenizer.get_decoder_prompt_idsc                C   s   t | ||||dS )N)return_timestampsreturn_languager  )_decode_asr)r;  model_outputsr  r  r  r   r   r   r  2  s   zWhisperTokenizer._decode_asrr  r  c                    st    dd|   dd}|d dd }t fdd	|D d}|dur0 |}td
| d|j|d |d S )z`Converts prompt text to IDs that can be passed to [`~WhisperForConditionalGeneration.generate`].r  rU  F)add_special_tokensr
  r   Nc                 3   s"    | ]}| j d  kr|V  qdS )r   N)r  )r   xrD  r   r   r  A  s     z2WhisperTokenizer.get_prompt_ids.<locals>.<genexpr>zJEncountered text in the prompt corresponding to disallowed special token: re  )tensor_type)stripnextrF  rX  convert_to_tensors)r;  r  return_tensorsbatch_encodingprompt_text_idsspecial_token_idr[  r   rD  r   get_prompt_ids;  s   
zWhisperTokenizer.get_prompt_idsr  r  c                 C   s@   t | to| o| d |k}|r|| v r| | |d  S g S | S )Nr   )r$  r    rW  )r  r  r  
has_promptr   r   r   r  I  s   zWhisperTokenizer._strip_prompt)
Nr  r  r  r  NFNNF)NNNrC  )NF)F)Fr  )r  )FNFr  FFFF)FFFF)NNT)r  )2r  
__module____qualname____doc__r  vocab_files_namesPRETRAINED_VOCAB_FILES_MAPpretrained_vocab_files_mapMAX_MODEL_INPUT_SIZESmax_model_input_sizesmodel_input_namesr8  propertyintrE  rL  ra  r%  boolrb  r   ru  ry  r   r{  r  r  r  r  staticmethodr  r  r  r   r  r  r  r  r   r  r  r   r  r  r  r  r  r  r  __classcell__r   r   r@  r   r	     s    (J*"	

0
	
O
* 
'


	$r	  c          '         s  d  fdd}g }| }d}|  dd }	g }
g }d}d}t| j}t|D ]\}}|d d	  }|d
kr@|d d	  }d}|	}d|v r||d \}}}||8 }|| }|r_|| |	 }|r|t|D ]}||	kr{|dury||	 | |k ry n|}qeg }g }t|D ]\}}||v r| |g}|dd }t|d}|durЈ r| kr|s|
	| t
|
}| |}||d< |	| g }
g }| }||d< | q	 q||	krV||	 | | } t| d} |r||krd}q|s|
r||k rd}q|d d	 du r| |d d	< q| |d d	 krq| |d d< |
	| |d
kr'|	| t
|
|\}}!| |}||d< |d
krEt| ||! |d< |	| g }
g }g }g }| }q|	| |d
krt|| | d}"|d t|k r~t||d  | d}#nd}#|	|"|#f qd|v r||| 7 }|r|
	| |d
kr|	| q'tdd |
D s| }g }
g }g }g }q'|
r|rtd t
|
|\}}!| |}||d< |d
krt| ||! |d< |	| ddd |D }$|s|r=|D ]}|s|d nt|d |d< |s|d q|d
kr5g }%|D ]
}|%|d  q"d|%i}&|$|&fS d|i}&|$|&fS i }&|$|&fS )z
    Internal method meant to only be used by asr pipeline. Handles all the little quirks specific to whisper to handle
    the various options not allowed in other seq2seq models
    Nc                      s    d d gddS )Nr~  )r   r  r  r   r   last_languager   r   	new_chunki  r  z_decode_asr.<locals>.new_chunk        rd  r   Fr  r   r,   token_timestampsstriderT  r  r   Tr  wordsc                 s   r  rC  r   )r   pr   r   r   r    r  z_decode_asr.<locals>.<genexpr>zWhisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.r~  c                 s   s    | ]}|d  V  qdS )r  Nr   )r   chunkr   r   r   r     s    chunks)rf  r*   r  r  tolistreversedr  rg  rN  r#   _find_longest_common_sequenceround_collate_word_timestampsr/  anyr  r  rZ  r  r  rY  )'	tokenizerr  r  r  r  r
  r  r  time_offsetr  previous_tokensprevious_token_timestampsskipright_stride_startr  chunk_idoutputr  r  last_timestampfirst_timestamp	chunk_lenstride_leftstride_rightr[  current_tokenscurrent_token_timestampsrH  r  r   resolved_tokensresolved_texttimeresolved_token_timestamps
start_timeend_time	full_text
new_chunksoptionalr   r  r   r  U  s  






















r  c                 C   s  | d }t |}g }|r|d }g }t| dd  D ]\}}d}	||ddf}
t |}td|| D ]]}|d }td|| }t||| | }t||| }td|| }t||}t||| }t |t |krqtdt||k}|| | }|dkr||	kr|}	||||f}
q1|
\}}}}|| d }|| d }|	|d |  ||d  }t |}|r|	|d |  ||d  |d  }q|	| |d u r|S t |dkr|	| ||fS |g fS )Nr   r   r  g     @ziThere is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.rT  )
r/  r  r!   maxrV  r  r  RuntimeErrorr  rY  )	sequencestoken_timestamp_sequencesleft_sequenceleft_lengthtotal_sequenceleft_token_timestamp_sequencetotal_token_timestamp_sequenceseq_idxright_sequencemax_max_indicesright_lengthrH  eps
left_start	left_stopleftright_start
right_stoprightmatchesmatchingleft_mid	right_midr   r   r   r  6  sZ   


r  c                    s.   t | ||\}}} fddt||D }|S )Nc                    s6   g | ]\}}| |d   d   |d  d fdqS )r   r  r   r  r   )r   r,   indicesr  r   r   r     s    z,_collate_word_timestamps.<locals>.<listcomp>)_combine_tokens_into_wordsr%   )r  r  r  r   r  _token_indicestimingsr   rK  r   r    s
   
r     "'“¡¿([{-   "'.。,，!！?？:：”)]}、r  r   prepend_punctuationsappend_punctuationsc                 C   s^   |du r| j }|du rd}|dv rt| |\}}}nt| |\}}}t||||| |||fS )z
    Groups tokens by word. Returns a tuple containing a list of strings with the words, and a list of `token_id`
    sequences with the tokens making up each word.
    Nr2   >   r   rm   r4   r   r@   r   )r   _split_tokens_on_unicode_split_tokens_on_spaces_merge_punctuations)r  r  r   rR  rS  r  word_tokensrN  r   r   r   rL    s   
rL  c                 C   s   | j |dd}d}g }g }g }g }g }d}	t|D ]=\}
}|| ||
 | j |dd}||vs=||	||  |krV|| || || g }g }|	t|7 }	q|||fS )zlCombine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.T)r  u   �r   )r  r  r#   rW  r/  )r  r  decoded_fullreplacement_charr  rW  rN  r&  current_indicesunicode_offset	token_idxr[  decodedr   r   r   rT    s,   





rT  c                 C   s   t | |\}}}g }g }g }t|||D ]I\}}	}
|	d | jk}|d}| dv }|s7|s7|s7t|dkrG|| ||	 ||
 q|d | |d< |d |	 |d |
 q|||fS )zLCombine tokens into words by splitting at whitespace and punctuation tokens.r   rU  z !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~r  )rT  r%   rv  
startswithr  r/  r#   rY  )r  r  subwordssubword_tokens_listsubword_indices_listr  rW  rN  subwordsubword_tokenssubword_indicesr  
with_spacepunctuationr   r   r   rU    s    



rU  c                 C   s  t | d }t | d }|dkrT| | drJ| |  |v rJ| | | |  | |< || ||  ||< || ||  ||< d| |< g ||< g ||< n|}|d8 }|dksd}d}|t | k r| | ds| | |v r| |  | | 7  < ||  || 7  < ||  || 7  < d| |< g ||< g ||< n|}|d7 }|t | k s^dd | D | dd< d	d |D |dd< d
d |D |dd< dS )z1Merges punctuation tokens with neighboring words.rT  r   r   rU  r~  c                 S      g | ]}|r|qS r   r   )r   r,   r   r   r   r     r   z'_merge_punctuations.<locals>.<listcomp>Nc                 S   rg  r   r   )r   r[  r   r   r   r     r   c                 S   rg  r   r   )r   idxr   r   r   r     r   )r/  r^  r  endswith)r  r  rJ  	prependedappendedrH  r`  r   r   r   rV    s:   

rV  rC  )NrP  rQ  ),r  r'  r  	functoolsr   typingr   r   r   r   numpyr  regexr3  tokenization_utilsr   r	   utilsr
   english_normalizerr   r   r  r  r   r)   
get_loggerr  r  r0   rg  r*  rj  rl  r	  r  r  r  r  r%  rL  rT  rU  rV  r   r   r   r   <module>   s  	
	
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVh      
bi
