U
    ,-e                  d   @   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 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dddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|cZd}d~ e D ddddddddddddZddgZ G dd deZ!dd Z"dddZ#dd Z$dee% e&e&e&dddZ'ee% dddZ(ee% dddZ)dd Z*dS )z!Tokenization classes for Whisper.    N)	lru_cache)ListOptionalTupleUnion   )
AddedTokenPreTrainedTokenizer)logging   )EnglishTextNormalizerz
vocab.jsonztokenizer.jsonz
merges.txtznormalizer.json)
vocab_fileZ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 ],}|| krf| | |d
|  |d7 }qfd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   q/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/models/whisper/tokenization_whisper.py
<listcomp>H   s     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pairsZ	prev_charcharr   r   r   	get_pairsP   s    r,   englishchinesegermanspanishrussiankoreanfrenchjapanese
portugueseturkishpolishcatalandutcharabicswedishitalianZ
indonesianZhindifinnishZ
vietnamesehebrewZ	ukrainiangreekZmalayczechromaniandanish	hungarianZtamil	norwegianthaiZurducroatian	bulgarian
lithuanianlatinZmaoriZ	malayalamZwelshslovakZteluguZpersianZlatvianZbengaliZserbianZazerbaijani	slovenianZkannadaestonianZ
macedonianZbretonZbasque	icelandicZarmenianZnepaliZ	mongolianZbosnianZkazakhZalbanianZswahiligalicianZmarathiZpunjabisinhalaZkhmerZshonaZyorubaZsomaliZ	afrikaansZoccitanZgeorgianZ
belarusianZtajikZsindhiZgujaratiZamharicZyiddishlaoZuzbekZfaroesezhaitian creoleZpashtoZturkmennynorskZmalteseZsanskritZluxembourgishmyanmarZtibetanZtagalogZmalagasyZassameseZtatarZhawaiianZlingalaZhausaZbashkirZjavaneseZ	sundanese)cenzhdeesrukofrjapttrplcanlarsvitidhifiviheukelmsr$   rodahutanothurhrbgltZlamimlcysktefalvZbnsrazslknetmkbreuishyneZmnr#   kksqswglmrpasikmZsnZyosoafockabetgsdguamyilouzfohtpsZtknnmtsalbmyZbotlZmgasttZhawlnZhabaZjwZsuc                 C   s   i | ]\}}||qS r   r   )r   codelanguager   r   r   
<dictcomp>   s      r   r   r^   r_   r   r   r   r   rk   r   rV   )ZburmeseZ	valencianZflemishZhaitianZletzeburgeschZpushtoZpanjabiZ	moldavianZmoldovanZ	sinhaleseZ	castilian	translate
transcribec                
       s  e Zd ZdZeZeZeZ	ddgZ
dJ fdd		Zeed
ddZdd Zdd ZdKeeedddZeee d
ddZdLee d
ddZdMee eee  eee d fddZdd Zdd Zdd  Zd!d" ZdNed
d$d%ZdOd&d'ZedPd(d)Z dQed*d+d,Z!d-d. Z"dReeeeed/ fd0d1Z#dSe$eee f eeeed2d3d4Z%d5d6 Z&dTeee e'e d7d8d9Z(dUd:d;Z)ed<d= Z*dVd?d@Z+dAdB Z,dWedDdEdFZ-e.ee eedGdHdIZ/  Z0S )XWhisperTokenizera  
    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*, defaults to `None`):
            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.
        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_idsZ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 5 Q R X dd | j D | _|| _	t
 | _dd | j D | _t|dd}| d	d
d }W 5 Q R X dd |D }tt|tt|| _i | _|	| _|d k	rnt|dd}t|| _W 5 Q R X nd | _td| _td| _|
| _t jf ||||||	d| || _|| _d S )NFT)lstriprstrip
normalizedspecialutf-8encodingc                 S   s   i | ]\}}||qS r   r   r   kvr   r   r   r   *  s      z-WhisperTokenizer.__init__.<locals>.<dictcomp>c                 S   s   i | ]\}}||qS r   r   r   r   r   r   r   -  s      
r   c                 S   s   g | ]}t | qS r   )tuplesplit)r   merger   r   r   r   0  s     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_space) 
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   r   r   kwargsZvocab_handleZmerges_handleZ
bpe_merges	__class__r   r   r     s^     

zWhisperTokenizer.__init__)returnc                 C   s
   t | jS N)r   r   r   r   r   r   
vocab_sizeM  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   ir   r   r   r   R  s      z.WhisperTokenizer.get_vocab.<locals>.<dictcomp>)r   r   updateadded_tokens_encoder)r   Zvocabr   r   r   	get_vocabQ  s    zWhisperTokenizer.get_vocabc           
         sd  | j kr j | S t|}t|}|s,|S t| fddd}| jkrNqL|\}}g }d}|t|k r"z|||}	W n, tk
r   |||d   Y q"Y nX ||||	  |	}|| |kr
|t|d k r
||d  |kr
|	||  |d7 }q^|	||  |d7 }q^t|}|}t|dkrBqLq,t|}q,d
|}| j |< |S )Nc                    s    j | tdS )Ninf)r   getfloat)pairr   r   r   <lambda>a      z&WhisperTokenizer.bpe.<locals>.<lambda>keyr   r       )r   r   r,   minr   r   index
ValueErrorextendr    join)
r   tokenr)   r*   ZbigramfirstsecondZnew_wordr   jr   r   r   bpeW  sB    


2




zWhisperTokenizer.bper   r   r   c                 C   s@   |dk	r|n| j | _ |dk	r |n| j| _|dk	r4|n| 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.
        Nr   )r   r   r   r   r   r   r   set_prefix_tokens  s    z"WhisperTokenizer.set_prefix_tokensc           	      C   sD  |  d}|  d}|  d}|  d}tt }| jd k	r| j | _| jtkr`t| j }nT| jt krv| j}n>t| jdk}t	d| j d|rt
t n
t
t  d| jd k	r| jtkrt	d	| j d
t |g}| jd k	r||d ||  | jd k	r.|| jdkr(|n| | js@|| |S )N<|startoftranscript|>z<|translate|>z<|transcribe|><|notimestamps|>r   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   r   r   r   TASK_IDSr    r   r   )	r   Zbos_token_idZtranslate_token_idZtranscribe_token_idZnotimestamps_token_idZlangsZlanguage_idZis_language_codeZbos_sequencer   r   r   prefix_tokens  s4    





*


zWhisperTokenizer.prefix_tokensc                 C   s0   |dkr| j | | jg S | j | | | jg S )z=Build model inputs from a sequence by appending eos_token_id.N)r  eos_token_id)r   token_ids_0token_ids_1r   r   r    build_inputs_with_special_tokens  s    z1WhisperTokenizer.build_inputs_with_special_tokens)r  r  already_has_special_tokensr   c                    sn   |rt  j||ddS dgt| j }dg}|dkrJ|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)r  r  r  r   Nr   )r   get_special_tokens_maskr   r  )r   r  r  r  Zprefix_onesZsuffix_onesr   r   r   r    s      z(WhisperTokenizer.get_special_tokens_maskc                    sZ   g }t  j|D ]B}d fdd|dD }|dd  |dD  q|S )zTokenize a string. c                 3   s   | ]} j | V  qd S r   )r   )r   r%   r   r   r   	<genexpr>  s    z-WhisperTokenizer._tokenize.<locals>.<genexpr>r   c                 s   s   | ]
}|V  qd S r   r   )r   Z	bpe_tokenr   r   r   r    s     r   )r   findallr   r   encoder   r   r   )r   text
bpe_tokensr   r   r   r   	_tokenize  s    "zWhisperTokenizer._tokenizec                 C   s   | j || j | jS )z0Converts a token (str) in an id using the vocab.)r   r   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   r   )r   r   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   r   )r   r  Z
normalizerr   r   r   
_normalize  s    
zWhisperTokenizer._normalize{Gz?c                    s~    j d d }g g}|D ]F}||krPd|| | 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    r   )r   	token_idsr  time_precisiontimestamp_beginoutputsr   	timestampr   r!  r   _decode_with_timestamps  s    
z(WhisperTokenizer._decode_with_timestampsc                 C   s\  g }t |}|jd dkr2t|jdkr2td| jd d }||k}t |dd |dd @ d d }|jd dkr| dkrg S t |d d d |krt |t |d d d }t |d d }|D ]|}||| }	t|	dkrR|	d 	 | }
|	d 	 | }| 
|	}	| |	}| |}|||
| || fd |}q|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   r   r"  wheresumr    item_preprocess_token_ids_decode_filter_timestamp_ids)r   r#  r$  offsetsr%  Ztimestamp_tokensZconsecutiveZ
last_sliceZcurrent_sliceZsliced_tokensZstart_timestamp_positionZ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   r   r$  r   r   r   M  s     z2WhisperTokenizer.timestamp_ids.<locals>.<listcomp>i  )r  r   )r   r$  r   r5  r   timestamp_idsD  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|>r  )r  _strip_prompt)r   r#  r  prompt_token_iddecoder_start_token_idr   r   r   r0  O  s
    

z&WhisperTokenizer._preprocess_token_idsc                 C   s   t | jd|S )Nr  )r   subr   )r   r#  r   r   r   r2  a  s    z&WhisperTokenizer._filter_timestamp_ids)r  clean_up_tokenization_spacesoutput_offsetsdecode_with_timestampsr   c                    sj   | j ||d}t j|f|||d|}	|r@| j|||d}	n
| |	}	|rf| 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`).
            kwargs (additional keyword arguments, *optional*):
                Will be passed to the underlying model specific decode method.
            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.
        Returns:
            `str`: The decoded sentence.
        r  )r  r<  r>  )r$  r  r5  )r  r3  )r0  r   r  r(  r2  r4  )r   r#  r  r<  r=  r$  r>  r   Zfiltered_idsr  r3  r   r   r   r  d  s0    $  

zWhisperTokenizer.decode)r#  r  	normalizer>  r   c                 K   s   | dd| _| j||d}g }g }|D ]L}	|r<|	| jkr<q(|	| jkrj|r^|| | g }||	 q(||	 q(|r|| | d|}
|r| |
}|S |
S d S )NZuse_source_tokenizerFr  r  )	popZ_decode_use_source_tokenizerr   r"  r   r    convert_tokens_to_stringr   r  )r   r#  r  r?  r>  r   Zfiltered_tokensZ	sub_textsZcurrent_sub_textr   r  Z
clean_textr   r   r   r1    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   cr   r   r   r     s     z=WhisperTokenizer.convert_tokens_to_string.<locals>.<listcomp>r   )r   )r   	bytearrayr  r   )r   tokensr  r   r   r   rA    s    
"z)WhisperTokenizer.convert_tokens_to_string)save_directoryfilename_prefixr   c              	   C   s  t j|s"td| d d S t j||r6|d ndtd  }t j||rX|d ndtd  }t j||rz|d ndtd  }t|dd	d
$}|t	j
| jddddd  W 5 Q R X d}t|dd	d
l}|d t| j dd dD ]D\}	}
||
krtd| d |
}|d|	d  |d7 }qW 5 Q R X | jd k	rt|dd	d
$}|t	j
| jddddd  W 5 Q R X |||fS )NzVocabulary path (z) should be a directory-r  r   r   r   wr   r   r   TF)indent	sort_keysensure_asciir   r   z#version: 0.2
c                 S   s   | d S )Nr   r   )kvr   r   r   r     r   z2WhisperTokenizer.save_vocabulary.<locals>.<lambda>r   zSaving vocabulary to zZ: BPE merge indices are not consecutive. Please check that the tokenizer is not corrupted!r   r   )ospathisdirloggererrorr   VOCAB_FILES_NAMESr   writer   dumpsr   sortedr   r   warningr   )r   rE  rF  r   Z
merge_filer   fr   writerr  Ztoken_indexr   r   r   save_vocabulary  sD       (


z WhisperTokenizer.save_vocabularyc                 K   s&   | d| j}|s|rd| }||fS )Nr   r   )r@  r   )r   r  Zis_split_into_wordsr   r   r   r   r   prepare_for_tokenization  s    z)WhisperTokenizer.prepare_for_tokenizationc                 C   s   dS )zv
        A simple chat template that ignores role information and just concatenates messages with EOS tokens.
        zM{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}r   r   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)r   r   r   r   c                 S   s   g | ]\}}|d  |fqS )r   r   )r   Zrankr   r   r   r   r   
  s     z;WhisperTokenizer.get_decoder_prompt_ids.<locals>.<listcomp>)r   r  	enumerate)r   r   r   Zno_timestampsZforced_tokensZ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`    s    zWhisperTokenizer._decode_asrr*  )r  c                    st    dd|   dd}|d dd }t fdd	|D d}|dk	r` |}td
| d|j|d |d S )z`Converts prompt text to IDs that can be passed to [`~WhisperForConditionalGeneration.generate`].r7  r   F)Zadd_special_tokensr   r   Nc                 3   s    | ]}| j d  kr|V  qdS )r   N)r"  )r   xr   r   r   r    s      z2WhisperTokenizer.get_prompt_ids.<locals>.<genexpr>zJEncountered text in the prompt corresponding to disallowed special token: r  )Ztensor_type)stripnextr   r   Zconvert_to_tensors)r   r  Zreturn_tensorsZbatch_encodingZprompt_text_idsZspecial_token_idr   r   r   r   get_prompt_ids  s    
zWhisperTokenizer.get_prompt_ids)r#  r9  r:  c                 C   s@   t | to| o| d |k}|r<|| kr8| | |d  S g S | S )Nr   )r   r   r   )r#  r9  r:  Z
has_promptr   r   r   r8  $  s    zWhisperTokenizer._strip_prompt)
Nr   r   r   r   NFNNF)NNN)N)NF)Fr  )r  )r  )F)FNFr  F)FFF)N)F)NNT)r*  )1__name__
__module____qualname____doc__rR  Zvocab_files_namesPRETRAINED_VOCAB_FILES_MAPZpretrained_vocab_files_mapMAX_MODEL_INPUT_SIZESZmax_model_input_sizesZmodel_input_namesr   propertyintr   r   r   r   boolr   r   r  r  r   r  r  r  r  r  r(  r4  r   r6  r0  r2  r  r   r1  rA  r   rY  rZ  r[  r]  r`  re  staticmethodr8  __classcell__r   r   r   r   r      s   &          J*"	    
 
0
     A   &'



	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|kr|d \}}}||8 }|| }|r|| |	 }|rt|D ],}||	kr|dk	r||	 | |k r q|}qg }g }t|D ]\}}||kr| |g}|dd }t|d}|dk	r" r| kr|s|
	| t
|
}| |}||d< |	| g }
g }| }||d< | n q||	kr||	 | | } t| d} |r||krd}n|s|
r||k rd}n|d d	 dkr$| |d d	< n| |d d	 kr8n| |d d< |
	| |d
krb|	| t
|
|\}}!| |}||d< |d
krt| ||! |d< |	| g }
g }g }g }| }nb|	| |d
krt|| | d}"|d t|k rt||d  | d}#nd}#|	|"|#f qd|kr<||| 7 }|rb|
	| |d
kr|	| qNtdd |
D sN| }g }
g }g }g }qN|
r|rtd t
|
|\}}!| |}||d< |d
krt| ||! |d< |	| ddd |D }$|s|r|D ]8}|s"|d nt|d |d< |s|d q|d
krxg }%|D ]}|%|d  qXd|%i}&nd|i}&n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   Zlast_languager   r   	new_chunkD  s    z_decode_asr.<locals>.new_chunk        r  r   FrD  r   r)   token_timestampsZstrider   r  r   Tr'  wordsc                 s   s   | ]
}|V  qd S r   r   )r   pr   r   r   r    s     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)r  r'   r"  r\  tolistreversedr  r  r   r    _find_longest_common_sequenceround_collate_word_timestampsr   anyrP  rV  r   r@  r   r   )'	tokenizerra  r^  r_  r$  rr  ry  rx  Ztime_offsetr%  Zprevious_tokensZprevious_token_timestampsskipZright_stride_startr"  Zchunk_idoutputr#  rt  Zlast_timestampZfirst_timestampZ	chunk_lenZstride_leftZstride_rightr   current_tokensZcurrent_token_timestampsr   r  r   Zresolved_tokensZresolved_texttimeZresolved_token_timestamps
start_timeend_time	full_textZ
new_chunksoptionalr   rq  r   r`  0  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rtdt||k}|| | }|dkrd||	krd|}	||||f}
qd|
\}}}}|| d }|| d }|	|d |  ||d  }t |}|r4|	|d |  ||d  |d  }q4|	| |d kr|S t |dkr|	| ||fS |g fS d S )Nr   r   rs  g     @ziThere is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.r   )
r   r\  r   maxr   r*  r+  RuntimeErrorr.  r   )	sequencesZtoken_timestamp_sequencesZleft_sequenceZleft_lengthZtotal_sequenceZleft_token_timestamp_sequenceZtotal_token_timestamp_sequenceZseq_idxZright_sequenceZmax_Zmax_indicesZright_lengthr   ZepsZ
left_startZ	left_stopleftZright_startZ
right_stoprightmatchesZmatchingZleft_midZ	right_midr   r   r   r|    sV    



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rt  r   r   r   |  s   z,_collate_word_timestamps.<locals>.<listcomp>)_combine_tokens_into_wordsr"   )r  rD  rt  r   rv  _token_indicesZtimingsr   r  r   r~  z  s
    
r~     "'“¡¿([{-   "'.。,，!！?？:：”)]}、)rD  r   prepend_punctuationsappend_punctuationsc                 C   s^   |dkr| j }|dkrd}|dkr4t| |\}}}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.
    Nr-   >   rE   r4   rR   r.   rP   )r   _split_tokens_on_unicode_split_tokens_on_spaces_merge_punctuations)r  rD  r   r  r  rv  word_tokensr  r   r   r   r    s    r  )rD  c                 C   s   | j |dd}d}g }g }g }g }g }d}	t|D ]z\}
}|| ||
 | j |dd}||ksz||	||  |kr2|| || || g }g }|	t|7 }	q2|||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    r   r   )r  rD  Zdecoded_fullreplacement_charrv  r  r  r  Zcurrent_indicesZunicode_offsetZ	token_idxr   decodedr   r   r   r    s.    




r  c                 C   s   t | |\}}}g }g }g }t|||D ]\}}	}
|	d | jk}|d}| dk}|sn|sn|snt|dkr|| ||	 ||
 q(|d | |d< |d |	 |d |
 q(|||fS )zLCombine tokens into words by splitting at whitespace and punctuation tokens.r   r   z !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~r   )r  r"   r  
startswithrc  r   r    r   )r  rD  ZsubwordsZsubword_tokens_listZsubword_indices_listrv  r  r  ZsubwordZsubword_tokensZsubword_indicesr   Z
with_spacepunctuationr   r   r   r    s     


r  c                 C   s  t | d }t | d }|dkr| | dr| |  |kr| | | |  | |< || ||  ||< || ||  ||< d| |< g ||< g ||< n|}|d8 }qd}d}|t | k r:| | ds,| | |kr,| |  | | 7  < ||  || 7  < ||  || 7  < d| |< g ||< g ||< n|}|d7 }qdd | D | dd< d	d |D |dd< d
d |D |dd< dS )z1Merges punctuation tokens with neighboring words.r   r   r   r   r  c                 S   s   g | ]}|r|qS r   r   )r   r)   r   r   r   r     s      z'_merge_punctuations.<locals>.<listcomp>Nc                 S   s   g | ]}|r|qS r   r   )r   r   r   r   r   r     s      c                 S   s   g | ]}|r|qS r   r   )r   idxr   r   r   r     s      )r   r  rc  endswith)rv  rD  r  Z	prependedZappendedr   r   r   r   r   r    s6    



r  )N)Nr  r  )+ri  r   rM  	functoolsr   typingr   r   r   r   numpyr*  regexr   Ztokenization_utilsr   r	   utilsr
   Zenglish_normalizerr   rR  rj  rk  r&   Z
get_loggerrf  rP  r,   r  r   r  r
  r   r`  r|  r~  rm  r   r  r  r  r  r   r   r   r   <module>   sF  	   
h    ] b
i   