
    qi                     *   d Z ddlZddlZddlZddlmZ ddlZddlm	Z	m
Z
mZmZmZ ddlmZ ddlmZ ddlmZ d	d
lmZmZ  ej.                  e      Zddd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&d'd(d)d*d+d,d-d.d/d0d1i d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSi dTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdui dvdwdxdydzd{d|d}d~d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 ej9                         D  ci c]  \  } }|| 
 c}} dd&d(dddddBdBdddd̜ZddgZ G dτ de      Z	 	 	 dde e!   de"dz  de"de"fdՄZ#ddքZ$dd؜dلZ%ddڄZ$dۄ Z&	 	 	 dde e!   de"dz  de"de"fd܄Z#de e!   fd݄Z'de e!   fdބZ(d߄ Z)dgZ*yc c}} w )z!Tokenization classes for Whisper.    N)	lru_cache)
AddedToken	Tokenizerdecoderspre_tokenizers
processors)BPE   )TokenizersBackend)logging   )BasicTextNormalizerEnglishTextNormalizerz
vocab.jsonztokenizer.jsonz
merges.txtznormalizer.json)
vocab_filetokenizer_filemerges_filenormalizer_file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malaycs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	mongolianbs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yuer   r   )burmese	valencianflemishhaitianletzeburgeschpushtopanjabi	moldavianmoldovan	sinhalese	castilianmandarin	translate
transcribec                   &    e Zd ZdZeZddgZeZ	 	 	 	 	 	 	 	 	 	 d1de	e
e	ef   z  dz  f fdZ	 d2de	f fd	Zd3d
Zed4d       Zd5defdZd Z	 	 	 	 	 	 	 	 d6dededz  dedededededede	f fdZdddddededede	f fdZd Zed5d       Zd7de	de	dz  dee	   fdZ	 d8de	dz  de	dz  d edz  fd!Zedee   fd"       Zd7dee   fd#Z 	 d9d$ee   d%ee   dz  d&edee   f fd'Z!d:d(Z"d) Z#d;d*e	fd+Z$d,ee   d-ed.efd/Z%ed0        Z& xZ'S )<WhisperTokenizerag	  
    Construct a "fast" Whisper tokenizer (backed by HuggingFace's *tokenizers* library).

    This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
    refer to this superclass for more information regarding those methods.

    Args:
        vocab_file (`str`, *optional*):
            Path to the vocabulary file.
        merges_file (`str`, *optional*):
            Path to the merges file.
        normalizer_file (`str`, *optional*):
            Path to the normalizer_file file.
        tokenizer_file (`str`, *optional*):
            Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
            contains everything needed to load the tokenizer.
        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. (Whisper tokenizer detect beginning of words by the preceding space).
        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_maskNFvocabc                 .   t        |t              rt        |dddd      n|}t        |t              rt        |dddd      n|}t        |t              rt        |dddd      n|}||ni | _        ||ng | _        t        t        | j                  | j                  d ddd            | _        t        j                  |      | j                  _
        t        j                         | j                  _        t        | 8  d|||||||	|
d| |1t        |d	      5 }t!        j"                  |      | _        d d d        nd | _        t'        j(                  d
      | _        || _        |	| _        |
| _        | j3                          y # 1 sw Y   IxY w)NFT)lstriprstrip
normalizedspecial )r   mergesdropoutcontinuing_subword_prefixend_of_word_suffixfuse_unk)add_prefix_space)	unk_token	bos_token	eos_tokenr   r   languagetaskpredict_timestampsutf-8encodingz<\|(\d+\.\d+)\|> )
isinstancestrr   _vocab_mergesr   r	   
_tokenizerr   	ByteLevelpre_tokenizerr   decodersuper__init__openjsonloadenglish_spelling_normalizerrecompiletimestamp_patr   r   r   set_prefix_tokens)selfr   r   r   r   r   r   r   r   r   r   kwargsvocab_handle	__class__s                b/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/whisper/tokenization_whisper.pyr  zWhisperTokenizer.__init__   s     )S) yuX\] 	 )S) yuX\] 	 )S) yuX\] 	  %0eb!'!3v#kk||*,#%	
 )7(@(@Rb(c%"*"4"4"6 
	
-+1
	
 
	
 &o8 KL3799\3J0K K 04D,ZZ(;< 	"4 K Ks    FFreturnc                 j   | j                   d   dz   }g g}d}d}d}	t        |      D ]  \  }
}||k\  r|t        ||z
  |z        }||k  r7|
dk\  xr ||
dz
     |k\  xr ||
dz
     |k\   }|r	|||z  z  }n|	}||	z  }|dd }|}	|}|j                  d||z   dd	       |j                  g        |d   j                  |        g }|D ]X  }t	        |t
              r|j                  |       %|r!|j                  t        |   ||
             H|j                  d       Z dj                  |      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              Nz<|z.2fz|>skip_special_tokensr   )	all_special_ids	enumeratefloatappendr  r  r  decodejoin)r  	token_idsr"  time_precisionsegment_sizetimestamp_beginoutputscur_max_timestampprev_segments_lenpenultimate_timestampitoken	timestamplast_was_single_endingdecoded_outputssr  s                   r  _decode_with_timestampsz(WhisperTokenizer._decode_with_timestamps  s    ..r2Q6$ #!), 	*HAu'!5?#:n"LM	00-.!V .!!a%(O;c	!a%@PTc@c9* .)^l-JJ),A))-BB)")#2,(9%$-!Y1B%BC#HKLr"""5)-	*0  	+A!S!&&q)&&uw~aM`~'ab&&r*	+ ww''    c                    g }dt        t        |            v r1t        |d      r%t        |j                        r|j	                         }t        j                  |      }|j                  d   dkD  r#t        |j                        dkD  rt        d      | j                  d   dz   }||k\  }t        j                  |dd |dd z        d   dz   }|j                  d   dk(  r|j                         dk  rg S t        j                  |      d   d   dz   |vr2t        j                  |t        j                  |      d   d   dz         }t        j                  |      d   d   }d}	d}
|D ]  }||| }t        |      dkD  r|d   j                         |z
  }|d   j                         |z
  }||	k  r-|dk\  xr ||dz
     |k\  xr ||dz
     |k\   }|r|
|z  }
n|
|	z  }
|}	| j                  |      }| j!                  |      }| j#                  |      }|j                  |||z  |
|z  z   ||z  |
|z  z   fd	       |} |S )
a  
        Compute offsets for a given tokenized input

        Args:
            token_ids (`Union[int, list[int], np.ndarray, torch.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.
            segment_size (`int`, *optional*, defaults to 1500):
                The number of features in the input mel spectrogram.
        torchcpur   r   z)Can only process a single input at a timer  Nr  textr3  )r  typehasattrcallabler;  nparrayshapelen
ValueErrorr#  wheresumr&  item_preprocess_token_ids_decode_filter_timestamp_ids)r  r)  r*  r+  offsetsr,  timestamp_tokensconsecutive
last_slicer.  r/  current_slicesliced_tokensstart_timestamp_positionend_timestamp_positionis_single_endingr=  s                    r  _compute_offsetsz!WhisperTokenizer._compute_offsetsH  s    c$y/**	50IhW`WdWdNe!IHHY'	??1!c)//&:Q&>HII..r2Q6$7hh/47G7KKLQORSSQ1$)9)=)=)?1)DIXX&'*2.2+E))K:J1KA1Nr1RUV1VWKXX./215
( 	'M%j?M=!A%+8+;+@+@+B_+T()6r):)?)?)AO)S&+.??'1Q (!*q.1_DuS]`aSaIbfuIu<$ ()\9))->>)$:! !% : := I||M211$7 $4~EHY\jHjj2^CFWZhFhh& 'J?	'B r8  c                 h    | j                  t        d      D cg c]
  }d||z  z   c}      S c c}w )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.
        i  z<|%.2f|>)convert_tokens_to_idsrange)r  r*  r1  s      r  timestamp_idszWhisperTokenizer.timestamp_ids  s5     ))X]^fXg*hSTJ!n:L,M*hii*hs   /r"  c                 t    |r5| j                  d      }| j                  d      }| j                  |||      }|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]`):
                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|><|startoftranscript|>)rW  _strip_prompt)r  r)  r"  prompt_token_iddecoder_start_token_ids        r  rI  z&WhisperTokenizer._preprocess_token_ids  sE     "889JKO%)%?%?@W%X"**9oG]^Ir8  c                 D    t        j                  | j                  d|      S )Nr   )r  subr  )r  r=  s     r  rK  z&WhisperTokenizer._filter_timestamp_ids  s    vvd(("d33r8  clean_up_tokenization_spacesoutput_offsetsr*  decode_with_timestamps	normalizebasic_normalizeremove_diacriticsc
           	      F   | j                  ||      }t        |   |f|||||	d|
}|r| j                  |||      }n@t	        |t
              r|D cg c]  }| j                  |       }}n| j                  |      }|r| j                  ||      }||dS |S c c}w )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]`):
                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. Will remove the previous tokens (pre-prompt)
                if present.
            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. If there are previous tokens (pre-prompt) to decode, they will only appear in the decoded
                text if they contain timestamp tokens.
            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"  rb  re  rf  rg  )r*  r"  )r*  )r=  rL  )rI  r  r'  r7  r  listrK  rU  )r  r)  r"  rb  rc  r*  rd  re  rf  rg  r  filtered_idsr=  trL  r  s                  r  r'  zWhisperTokenizer.decode  s    d 11 3 2 

 w~
 3)E+/
 
 "//^Qd 0 D
 $%?CD!2215DD11$7 ++In+UG W55 Es   B)re  rf  rg  c                ~    t        |   |i |}|r| j                  |      }|S |r| j                  ||      }|S |S )Nrg  )r  rJ  re  rf  )	r  re  rf  rg  argsr  r=  
clean_textr  s	           r  rJ  zWhisperTokenizer._decode  sS     w//-J--dFW-XJKr8  c                 <    t        | j                        } ||      S )z
        Normalize a given string using the `EnglishTextNormalizer` class, which performs commons transformation on
        english text.
        )r   r  )r  r=  
normalizers      r  re  zWhisperTokenizer.normalize  s    
 +4+K+KL
$r8  c                 *    t        |      } ||       S )z
        Normalize a given string using the `BasicTextNormalizer` class, which performs commons transformation on
        multilingual text.
        rm  )r   )r=  rg  rq  s      r  rf  z WhisperTokenizer.basic_normalize  s     );LM
$r8  save_directoryfilename_prefixc           	         t         j                  j                  |      st        j	                  d| d       y t         j                  j                  ||r|dz   ndt        d   z         }t         j                  j                  ||r|dz   ndt        d   z         }t         j                  j                  ||r|dz   ndt        d   z         }t        |dd	
      5 }|j                  t        j                  | j                  ddd      dz          d d d        t        |dd	
      5 }|j                  d       |j                  d | j                  D               d d d        | j                  Lt        |dd	
      5 }|j                  t        j                  | j                  ddd      dz          d d d        |||fS # 1 sw Y   xY w# 1 sw Y   rxY w# 1 sw Y   &xY w)NzVocabulary path (z) should be a directory-r   r   r   r   wr   r  r  TF)indent	sort_keysensure_ascii
z#version: 0.2
c              3   D   K   | ]  }d j                  |      dz     yw) r{  N)r(  ).0
merge_pairs     r  	<genexpr>z3WhisperTokenizer.save_vocabulary.<locals>.<genexpr>5  s     Yjchhz2T9Ys    )ospathisdirloggererrorr(  VOCAB_FILES_NAMESr  writer  dumpsr  
writelinesr  r  )r  rs  rt  r   
merge_filer   fwriters           r  save_vocabularyz WhisperTokenizer.save_vocabulary!  s   ww}}^,LL,^,<<STUWW\\o_s22QbcoQpp

 WW\\o_s22QbcpQqq

 '',,o_s22QbctQuu
 *cG4 	bGGDJJt{{1SXY\``a	b *cG4 	ZLL*+YDLLYY	Z ++7osW= JJt??UYhmnquu
 J88	b 	b	Z 	Z
 s$   6G '4G=6G G	GG!r   r   r   c           	         ||n| j                   | _         ||n| j                  | _        ||n| j                  | _        | j                  }| j	                  |      }| j
                  }| j                  }dj                  |D cg c]  }| d	 c}      }	t        j                  |	 d| d|	 d| d||fgt        ||            | j                  _        yc c}w )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 = WhisperTokenizerFast.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}  z:0z $A:0 z $A:0 $B:1 z:1)singlepairspecial_tokens)r   r   r   prefix_tokensconvert_ids_to_tokensr   eos_token_idr(  r   TemplateProcessingzipbackend_tokenizerpost_processor)
r  r   r   r   prefix_token_idsprefixeseosr  r2  prefix_templates
             r  r  z"WhisperTokenizer.set_prefix_tokens?  s    , %-$8dmm ,D$))	8J8V"4\`\s\s----.>?nn((((h#GUugRL#GH0:0M0M%&fSE4#$KuB7l#X/01
- $Hs   Cc           	         | j                  d      }| j                  d      }| j                  d      }| j                  d      }t        t        j                               }| j                  | j                  j                         | _        | j                  t        v rt        | j                     }n| j                  t        j                         v r| j                  }nnt        | j                        dk(  }t        d| j                   d|rt        t        j                               nt        t        j                                d      | j                  1| j                  t        vrt        d	| j                   d
t               |g}| j                  &|j                  |dz   |j                        z          | j                  "|j                  | j                  dk(  r|n|       | j                  s|j                  |       |S )Nr\  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   )rW  tuple	LANGUAGESkeysr   lowerTO_LANGUAGE_CODEvaluesrD  rE  ri  r   TASK_IDSr&  indexr   )	r  bos_token_idtranslate_token_idtranscribe_token_idnotimestamps_token_idlangslanguage_idis_language_codebos_sequences	            r  r  zWhisperTokenizer.prefix_tokensg  s    112IJ!77H"889IJ $ : :;M Ninn&'==$ MM//1DM}} 00.t}}="2"9"9";;"mm#&t}}#5#:  ,T]]O <;K-4467QUVfVkVkVmQnoopr 
 99 yy( #5dii[@UV^U_!`aa$~==$q 05;;{3K KL99 tyyL7P 3Vhi&& 56r8  c                     || j                   |z   | j                  gz   S | j                   |z   |z   | j                  gz   S )z=Build model inputs from a sequence by appending eos_token_id.)r  r  )r  token_ids_0token_ids_1s      r   build_inputs_with_special_tokensz1WhisperTokenizer.build_inputs_with_special_tokens  sK    %%3t7H7H6III!!K/+=ARAR@SSSr8  r  r  already_has_special_tokensc                     |rt         |   ||d      S dgt        | j                        z  }dg}||dgt        |      z  z   |z   S |dgt        |      z  z   dgt        |      z  z   |z   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   r   )r  get_special_tokens_maskrD  r  )r  r  r  r  prefix_onessuffix_onesr  s         r  r  z(WhisperTokenizer.get_special_tokens_mask  s    & &72'[]a 3   cC 2 233c1#K(8"89KGGqcC$445!s;?O9OPS^^^r8  c                     | j                  |||        | j                  dd  }t        |      D cg c]  \  }}|dz   |f }}}|S c c}}w )N)r   r   r   r   )r  r  r$  )r  r   r   no_timestampsforced_tokensrankr2  forced_decoder_idss           r  get_decoder_prompt_idsz'WhisperTokenizer.get_decoder_prompt_ids  sa    D8TaPab
 **12.CL]C[\KD%tax/\\!! ]s   A	c                "    t        | ||||      S )N)return_timestampsreturn_languager*  )_decode_asr)r  model_outputsr  r  r*  s        r  r  zWhisperTokenizer._decode_asr  s    /+)
 	
r8  r=  c                        dd|j                         z   d      }|d   dd }t         fd|D        d      }|  j                  |      }t        d	| d
      |j	                  |       |d   S )z`Converts prompt text to IDs that can be passed to [`~WhisperForConditionalGeneration.generate`].r[  r}  F)add_special_tokensr   r   Nc              3   H   K   | ]  }|j                   d    k\  s|  yw)r   N)r#  )r~  xr  s     r  r  z2WhisperTokenizer.get_prompt_ids.<locals>.<genexpr>  s$      \qqDDXDXYZD[?[ \s   ""zJEncountered text in the prompt corresponding to disallowed special token: r  )tensor_type)stripnextr  rE  convert_to_tensors)r  r=  return_tensorsbatch_encodingprompt_text_idsspecial_token_idr2  s   `      r  get_prompt_idszWhisperTokenizer.get_prompt_ids  s    /tzz|1CX]^ )5ab9 \O \^bc'../?@Eijoippqrss))n)Ek**r8  r)  r^  r_  c                     t        |t              s| j                  |      }|s|S |d   |k(  }|r||v r||j                  |      d  S g S |S )Nr   )r  ri  _convert_to_listr  )r  r)  r^  r_  
has_prompts        r  r]  zWhisperTokenizer._strip_prompt  sc    )T*--i8I q\_4
%2 1G!H!JKK	r8  c                     t        | d      r| j                         j                         } t        | t        j
                        r| j                         } | S )Nnumpy)r?  r;  r  r  rA  ndarraytolist)r)  s    r  r  z!WhisperTokenizer._convert_to_list  sD     9g&!--/Ii,!((*Ir8  )
NNN<|endoftext|>r  r  FNNF)F{Gz?  )r  r  )r  )F)FNFr  FFFFN)NNN)NF)NNT)rA  )(__name__
__module____qualname____doc__r  vocab_files_namesmodel_input_namesr	   modelr  dictintr  r7  rU  r   rY  boolrI  rK  r%  r'  rJ  re  staticmethodrf  r  r  r  propertyri  r  r  r  r  r  r  r]  r  __classcell__)r  s   @r  r   r      s   $L *$&67E .2!!! F!T#s(^#d*F!T W[.(	.(bBH j jD &4 %*48$ $', %"'P "P '+Tk	P
 P P !%P P P  P 
Pf (-egl $?C`d	     9c 9C$J 9Z_`cZd 9> gk&
d
&
14t&
X\_cXc&
P tCy  DTQUVYQZ T pu_9_379t3C_hl_	c_>"
+3 +tCy 3 `c $  r8  r   tokensr   prepend_punctuationsappend_punctuationsc                     || j                   }|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.
    r   >   r   rQ   r   r   r#   r   r   _split_tokens_on_unicode_split_tokens_on_spaces_merge_punctuations	tokenizerr  r   r  r  wordsword_tokenstoken_indicess           r  _combine_tokens_into_wordsr    o     %%QQ,DYPV,W){M,CIv,V){M{M;OQde+},,r8  c           
         | d   }t        |      }g }rd   g }t        | dd        D ]w  \  }d}||ddf}t        |      }	t        d||	z         D ]  }
|
dz  }t        d||
z
        t	        |||	z   |
z
        }t        j                  ||       }t        d|
|z
        t	        |	|
      }t        j                  ||       t        |      t              k7  rt        d      r#t        fdt        |      D              }nt        j                  |k(        }||
z  |z   }|dkD  s||kD  s|}||f} |\  }}|z   dz  }|z   dz  }|j                  |d |        ||d  }t        |      }sYj                  d |        dz      |d  z |j                  |       |S t              dkD  rj                         ||fS |g fS )Nr   r   r       @iThere is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference.c              3   f   K   | ](  \  }}||   k(  r|z      d z      |z      k  rd  * ywr   Nr  	r~  idxelem
left_startleft_token_timestamp_sequencerightright_startseq_idxtoken_timestamp_sequencess	      r  r  z0_find_longest_common_sequence.<locals>.<genexpr>V  S      !Tc
*9*s:JK4Wq[A+PSBSTU	    .1r  
rD  r$  rX  maxminrA  rB  RuntimeErrorrG  extend	sequencesr  left_sequenceleft_lengthtotal_sequencetotal_token_timestamp_sequenceright_sequencemax_max_indicesright_lengthr1  eps	left_stopleft
right_stopmatchesmatchingleft_mid	right_midr  r  r  r  r  s    `                 @@@@@r  _find_longest_common_sequencer     v    aLMm$KN (A!(D%)+&#,Yqr]#; [_"KA6< >*q+45 (	OAg+C
 Qa0JK|)Ca)GHI88M*Y?@Da[1K\1-JHH^K
CDE 4yCJ&"  )   %.t_  &&/{S(H{x$)9k:NQ(	OT <G8YZ 
*q0+-!3	mIX67&yz2-($*112OPYQY2Z[,EgPQk,RS\S],^)w[_z -( (
$%)&--.KL===r!!r8  r  )r+  c          	      X	  / d//fd}g } |       }d}	| j                  d      dz   }
g }g }d}d}t        | j                        }| j                  d      }| j                  d      }t        |      D ]<  \  }}|d	   d
   j	                         }| j                  |||      }|dk(  r|d   d
   j	                         }d}|
}d}d}d}d|v rF|d   \  }}}|	|z  }	||z
  }|r||z  |
z   }|r't        |      D ]  }||
k\  s	|||
z
  |z  |k  r n|} g }g } t        |      D ]/  \  }!}||v r| j                  |g      }"|"dd }"t        j                  |"      }#|#_/rU|#/k7  rP|sN|j                  |       t        |      }$| j                  |$      }%|%|d<   |j                  |       g }g } |       }|#|d<   |#/||
k\  r*t        ||
z
  |z        }&|&|k  r2|!dk\  xr ||!dz
     |
k\  xr ||!dz
     |
k\   }'|'r	|||z  z  }n|}||z  }|}|&}||
z
  |z  |	z   |z   }(t        |(d      }(|r	||k\  rd}|s|r	||k  rd}|d   d
   
|(|d   d
<   /|(|d   d
   k(  r<|(|d   d<   |j                  |       |dk(  r|j                  |        t        ||      \  }$})| j                  |$      }%|%|d<   |dk(  rt        | |$|)/|      |d<   |j                  |       g }g }g }g }  |       }|j                  |       |dk(  s|!d
k(  rt        d|	z   d      }*nt        |!dz
     |	z   d      }*t        |!   |	z   d      }+| j                  |*|+f       2 d|v r|	z
  z  }	|r+|j                  |       |dk(  s|j                  |        t        d |D              r. |       }g }g }g }g } ? |rd|rt         j#                  d       t        ||      \  }$})| j                  |$      }%|%|d<   |dk(  rt        | |$|)/|      |d<   |j                  |       dj%                  d |D              },|s|rr|D ];  }|s|j'                  d       nt)        |d         |d<   |r+|j'                  d       = |dk(  r%g }-|D ]  }|-j+                  |d           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                       d d gddS )Nr   )r   r3  r=  r  )last_languages   r  	new_chunkz_decode_asr.<locals>.new_chunk  s    )tbQQr8  r  r  r   Fr[  r\  r  r   wordtoken_timestampsstrider  r   r=  r   Tr3  r  c              3       K   | ]  }|  y wr  r  )r~  ps     r  r  z_decode_asr.<locals>.<genexpr>Q  s     1Aa1s   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              3   &   K   | ]	  }|d      yw)r=  Nr  )r~  chunks     r  r  z_decode_asr.<locals>.<genexpr>k  s     :%f:s   chunks)rW  setr#  r$  r  r]  reversedr'  r  getr&  r   r%  round_collate_word_timestampsanyr  warningr(  popr  r  )0r  r  r  r  r*  r+  r%  r-  r,  time_offsetr,  previous_tokensprevious_token_timestampsskipright_stride_startr#  r^  r_  chunk_idoutputr)  r'  last_timestampfirst_timestampr.  r/  r0  	chunk_lenstride_leftstride_rightr2  current_tokenscurrent_token_timestampsr1  r=  r   resolved_tokensresolved_textr3  r4  timeresolved_token_timestamps
start_timeend_time	full_text
new_chunksoptionalr$  s0                                                  @r  r  r    si   $ MR FKEK556HIAMOO "D)334O556GHO&<<=TU%m4 l*& 8$Q'..0	++IH^_	&%&89!<CCE
 )   #v39(3C0I{L;&K!*\!9 "-">"P%i0 	/E/ +6!&!8N JM_ _!).	/ #%  "), l	LHAu ' ''0Abz$==.' %])BK\'..~>*G*X(1(8(8(I(5fe, +-)+ )(0E*%$,M /) "5?#:n"LM	00-.!V .!!a%(O;c	!a%@PTc@c9* .)^l-JJ),A))-BB)(9%$-!/>AKORccT1~!e~&=  Do%/2I D;'*2,0E+&q) u[1!44 04k*1-'..~>,65<<=UVEb+-FFB)B )2(8(8(I(5f,6-E )?<UWdfu.E'N e, +-)+461350 )
 %%e,$.Av%*3+<a%@
%*+;AE+B[+PRS%T
$%5a%8;%FJH,33Z4JKYl	L\ v9|33K "">2 F*)001IJ111KE ON(*%')$Yl*\ NN]
 6S66
22 "((9%f&5?,E}VeE'N 	e :6::IO 	&E$		+&%*5+=%>k""		*%	& &J 2!!%.12 *-H
 h !&)H h hr8  c           
         | d   }t        |      }g }rd   g }t        | dd        D ]w  \  }d}||ddf}t        |      }	t        d||	z         D ]  }
|
dz  }t        d||
z
        t	        |||	z   |
z
        }t        j                  ||       }t        d|
|z
        t	        |	|
      }t        j                  ||       t        |      t              k7  rt        d      r#t        fdt        |      D              }nt        j                  |k(        }||
z  |z   }|dkD  s||kD  s|}||f} |\  }}|z   dz  }|z   dz  }|j                  |d |        ||d  }t        |      }sYj                  d |        dz      |d  z |j                  |       |S t              dkD  rj                         ||fS |g fS )Nr   r   r  r  r  c              3   f   K   | ](  \  }}||   k(  r|z      d z      |z      k  rd  * ywr  r  r  s	      r  r  z0_find_longest_common_sequence.<locals>.<genexpr>  r  r  r  r	  r  s    `                 @@@@@r  r   r     r!  r8  c           	          t        | ||      \  }}}|rd|ini }t        ||      D 	
cg c]   \  }	}
|	||
d      d   ||
d      d   fd|" }}	}
|S c c}
}	w )Nr   r   r  r   r<  )r  r  )r  r  r'  r   r  r  _r  optional_language_fieldr&  indicestimingss               r  r2  r2    s    8FHUE1m8Gz84R !6 D'	 *71:6q9;KGTVK;XYZ;[\	
 &	
G  Ns   %Ac                     || j                   }|d}|dv rt        | |      \  }}}nt        | |      \  }}}t        |||||       |||fS r  r  r  s           r  r  r  	  r  r8  c                    | j                  |d      }d}g }g }g }g }g }d}	t        |      D ]  \  }
}|j                  |       |j                  |
       | j                  |d      }||vs||	|j                  |      z      |k(  sZ|j                  |       |j                  |       |j                  |       g }g }|	t	        |      z  }	 |||fS )zlCombine tokens into words by splitting at any position where the tokens are decoded as valid unicode points.T)rd  u   �r   )r'  r$  r&  r  rD  )r  r  decoded_fullreplacement_charr  r  r  rB  current_indicesunicode_offset	token_idxr2  decodeds                r  r  r  #  s    ##F4#HLEKMNON%f- +	5e$y)"">$"O G+NW]];K-LLMQaaLL!~.  1N Oc'l*N+  +},,r8  c                    t        | |      \  }}}g }g }g }t        |||      D ]  \  }}	}
|	d   | j                  k\  }|j                  d      }|j	                         dv }|s|s|st        |      dk(  r4|j                  |       |j                  |	       |j                  |
       |d   |z   |d<   |d   j                  |	       |d   j                  |
        |||fS )zLCombine tokens into words by splitting at whitespace and punctuation tokens.r   r}  z !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~r  )r  r  r  
startswithr  rD  r&  r  )r  r  subwordssubword_tokens_listsubword_indices_listr  r  r  subwordsubword_tokenssubword_indicesr   
with_spacepunctuations                 r  r  r  B  s    :RS\^d:e7H!#7EKM47BUWk4l 60 #y'='=='',
mmo)MMjK3u:?LL!~.  1b	G+E"IO"">2"$$_56 +},,r8  c                    t        |       dz
  }t        |       dz
  }|dk\  rp| |   j                  d      rO| |   j                         |v r:| |   | |   z   | |<   ||   ||   z   ||<   ||   ||   z   ||<   d| |<   g ||<   g ||<   n|}|dz  }|dk\  rpd}d}|t        |       k  rq| |   j                  d      sG| |   |v r@| |xx   | |   z  cc<   ||xx   ||   z  cc<   ||xx   ||   z  cc<   d| |<   g ||<   g ||<   n|}|dz  }|t        |       k  rq| D cg c]  }|s|	 c}| dd |D cg c]  }|s|	 c}|dd |D 	cg c]  }	|	s|		 c}	|dd yc c}w c c}w c c}	w )z1Merges punctuation tokens with neighboring words.r  r   r   r}  r   N)rD  r]  r  endswith)
r  r  rR  	prependedappendedr1  jr&  r2  r  s
             r  r  r  Z  s    	E
QAE
QA
q&8s#a(8I(EQx%(*E!Hq	F1I-F1I gaj0GAJE!HF1IGAJA	Q q& 	
A	A
c%j.Qx  %%(h*>!Ha H1I"IAJ'!*$JE!HF1IGAJA	Q c%j. "'/$/E!H$*45e4F1I!(0#C#0GAJ 040s$   E!E/E7EE"E")Nu   "'“¡¿([{-u   "'.。,，!！?？:：”)]}、r  )+r  r  r  r  	functoolsr   r  rA  
tokenizersr   r   r   r   r   tokenizers.modelsr	   tokenization_utils_tokenizersr   utilsr   english_normalizerr   r   
get_loggerr  r  r  r  itemsr  r  r   ri  r  r  r  r   r  r2  r  r  r  __all__)coder   s   00r  <module>ru     s   (  	 	   R R ! >  J 
		H	% &(	 e)e)e 	(e 	)	e
 	)e 	(e 	(e 	*e 	,e 	)e 	(e 	)e 	'e 	(e 	)e  	)!e" 	,#e$ 	'%e& 	)'e( 	,)e* 	(+e, 	+-e. 	'/e0 	'1e2 	'3e4 	*5e6 	(7e8 	+9e: 	';e< 	+=e> 	&?e@ 	&AeB 	*CeD 	+EeF 	,GeH 	'IeJ 	'KeL 	+MeN 	'OeP 	(QeR 	(SeT 	)UeV 	)WeX 	)YeZ 	)[e\ 	-]e^ 	+_e` 	)aeb 	*ced 	,eef 	(geh 	(iej 	+kel 	*men 	(oep 	+qer 	)set 	(uev 	*wex 	)yez 	*{e| 	)}e~ 	)e@ 	)AeB 	'CeD 	'EeF 	(GeH 	(IeJ 	+KeL 	)MeN 	*OeP 	,QeR 	'SeT 	(UeV 	*WeX 	)YeZ 	)[e\ 	%]e^ 	'_e` 	)aeb 	
ced 	(eef 	)geh 	)iej 	)kel 











Ie	P,5OO,=>.$x~>   &M	( M	f   0A-I- Dj- 	-
 -4u"p os yxu"p&   0A-I- Dj- 	-
 -4-S	 ->-tCy -0#1L 
_' ?s   	H