tokenization_whisper.py 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  1. # Copyright 2022 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Tokenization classes for Whisper."""
  15. import json
  16. import os
  17. import re
  18. from functools import lru_cache
  19. import numpy as np
  20. from tokenizers import AddedToken, Tokenizer, decoders, pre_tokenizers, processors
  21. from tokenizers.models import BPE
  22. from ...tokenization_utils_tokenizers import TokenizersBackend
  23. from ...utils import logging
  24. from .english_normalizer import BasicTextNormalizer, EnglishTextNormalizer
  25. logger = logging.get_logger(__name__)
  26. VOCAB_FILES_NAMES = {
  27. "vocab_file": "vocab.json",
  28. "tokenizer_file": "tokenizer.json",
  29. "merges_file": "merges.txt",
  30. "normalizer_file": "normalizer.json",
  31. }
  32. LANGUAGES = {
  33. "en": "english",
  34. "zh": "chinese",
  35. "de": "german",
  36. "es": "spanish",
  37. "ru": "russian",
  38. "ko": "korean",
  39. "fr": "french",
  40. "ja": "japanese",
  41. "pt": "portuguese",
  42. "tr": "turkish",
  43. "pl": "polish",
  44. "ca": "catalan",
  45. "nl": "dutch",
  46. "ar": "arabic",
  47. "sv": "swedish",
  48. "it": "italian",
  49. "id": "indonesian",
  50. "hi": "hindi",
  51. "fi": "finnish",
  52. "vi": "vietnamese",
  53. "he": "hebrew",
  54. "uk": "ukrainian",
  55. "el": "greek",
  56. "ms": "malay",
  57. "cs": "czech",
  58. "ro": "romanian",
  59. "da": "danish",
  60. "hu": "hungarian",
  61. "ta": "tamil",
  62. "no": "norwegian",
  63. "th": "thai",
  64. "ur": "urdu",
  65. "hr": "croatian",
  66. "bg": "bulgarian",
  67. "lt": "lithuanian",
  68. "la": "latin",
  69. "mi": "maori",
  70. "ml": "malayalam",
  71. "cy": "welsh",
  72. "sk": "slovak",
  73. "te": "telugu",
  74. "fa": "persian",
  75. "lv": "latvian",
  76. "bn": "bengali",
  77. "sr": "serbian",
  78. "az": "azerbaijani",
  79. "sl": "slovenian",
  80. "kn": "kannada",
  81. "et": "estonian",
  82. "mk": "macedonian",
  83. "br": "breton",
  84. "eu": "basque",
  85. "is": "icelandic",
  86. "hy": "armenian",
  87. "ne": "nepali",
  88. "mn": "mongolian",
  89. "bs": "bosnian",
  90. "kk": "kazakh",
  91. "sq": "albanian",
  92. "sw": "swahili",
  93. "gl": "galician",
  94. "mr": "marathi",
  95. "pa": "punjabi",
  96. "si": "sinhala",
  97. "km": "khmer",
  98. "sn": "shona",
  99. "yo": "yoruba",
  100. "so": "somali",
  101. "af": "afrikaans",
  102. "oc": "occitan",
  103. "ka": "georgian",
  104. "be": "belarusian",
  105. "tg": "tajik",
  106. "sd": "sindhi",
  107. "gu": "gujarati",
  108. "am": "amharic",
  109. "yi": "yiddish",
  110. "lo": "lao",
  111. "uz": "uzbek",
  112. "fo": "faroese",
  113. "ht": "haitian creole",
  114. "ps": "pashto",
  115. "tk": "turkmen",
  116. "nn": "nynorsk",
  117. "mt": "maltese",
  118. "sa": "sanskrit",
  119. "lb": "luxembourgish",
  120. "my": "myanmar",
  121. "bo": "tibetan",
  122. "tl": "tagalog",
  123. "mg": "malagasy",
  124. "as": "assamese",
  125. "tt": "tatar",
  126. "haw": "hawaiian",
  127. "ln": "lingala",
  128. "ha": "hausa",
  129. "ba": "bashkir",
  130. "jw": "javanese",
  131. "su": "sundanese",
  132. "yue": "cantonese",
  133. }
  134. # language code lookup by name, with a few language aliases
  135. TO_LANGUAGE_CODE = {
  136. **{language: code for code, language in LANGUAGES.items()},
  137. "burmese": "my",
  138. "valencian": "ca",
  139. "flemish": "nl",
  140. "haitian": "ht",
  141. "letzeburgesch": "lb",
  142. "pushto": "ps",
  143. "panjabi": "pa",
  144. "moldavian": "ro",
  145. "moldovan": "ro",
  146. "sinhalese": "si",
  147. "castilian": "es",
  148. "mandarin": "zh",
  149. }
  150. TASK_IDS = ["translate", "transcribe"]
  151. class WhisperTokenizer(TokenizersBackend):
  152. """
  153. Construct a "fast" Whisper tokenizer (backed by HuggingFace's *tokenizers* library).
  154. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
  155. refer to this superclass for more information regarding those methods.
  156. Args:
  157. vocab_file (`str`, *optional*):
  158. Path to the vocabulary file.
  159. merges_file (`str`, *optional*):
  160. Path to the merges file.
  161. normalizer_file (`str`, *optional*):
  162. Path to the normalizer_file file.
  163. tokenizer_file (`str`, *optional*):
  164. Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
  165. contains everything needed to load the tokenizer.
  166. unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  167. The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
  168. token instead.
  169. bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  170. The beginning of sequence token. The `decoder_start_token_id` is used to set the first token as
  171. `"<|startoftranscript|>"` when generating.
  172. eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
  173. The end of sequence token.
  174. add_prefix_space (`bool`, *optional*, defaults to `False`):
  175. Whether or not to add an initial space to the input. This allows to treat the leading word just as any
  176. other word. (Whisper tokenizer detect beginning of words by the preceding space).
  177. language (`str`, *optional*):
  178. The language of the transcription text. The corresponding language id token is appended to the start of the
  179. sequence for multilingual speech recognition and speech translation tasks, e.g. for Spanish the token
  180. `"<|es|>"` is appended to the start of sequence. This should be used for multilingual fine-tuning only.
  181. task (`str`, *optional*):
  182. Task identifier to append at the start of sequence (if any). This should be used for mulitlingual
  183. fine-tuning, with `"transcribe"` for speech recognition and `"translate"` for speech translation.
  184. predict_timestamps (`bool`, *optional*, defaults to `False`):
  185. Whether to omit the `<|notimestamps|>` token at the start of the sequence.
  186. """
  187. vocab_files_names = VOCAB_FILES_NAMES
  188. model_input_names = ["input_ids", "attention_mask"]
  189. model = BPE
  190. def __init__(
  191. self,
  192. vocab: str | dict[str, int] | None = None,
  193. merges=None,
  194. normalizer_file=None,
  195. unk_token="<|endoftext|>",
  196. bos_token="<|endoftext|>",
  197. eos_token="<|endoftext|>",
  198. add_prefix_space=False,
  199. language=None,
  200. task=None,
  201. predict_timestamps=False,
  202. **kwargs,
  203. ):
  204. bos_token = (
  205. AddedToken(bos_token, lstrip=False, rstrip=False, normalized=False, special=True)
  206. if isinstance(bos_token, str)
  207. else bos_token
  208. )
  209. eos_token = (
  210. AddedToken(eos_token, lstrip=False, rstrip=False, normalized=False, special=True)
  211. if isinstance(eos_token, str)
  212. else eos_token
  213. )
  214. unk_token = (
  215. AddedToken(unk_token, lstrip=False, rstrip=False, normalized=False, special=True)
  216. if isinstance(unk_token, str)
  217. else unk_token
  218. )
  219. self._vocab = vocab if vocab is not None else {}
  220. self._merges = merges if merges is not None else []
  221. self._tokenizer = Tokenizer(
  222. BPE(
  223. vocab=self._vocab,
  224. merges=self._merges,
  225. dropout=None,
  226. continuing_subword_prefix="",
  227. end_of_word_suffix="",
  228. fuse_unk=False,
  229. )
  230. )
  231. self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space)
  232. self._tokenizer.decoder = decoders.ByteLevel()
  233. super().__init__(
  234. unk_token=unk_token,
  235. bos_token=bos_token,
  236. eos_token=eos_token,
  237. add_prefix_space=add_prefix_space,
  238. normalizer_file=normalizer_file,
  239. language=language,
  240. task=task,
  241. predict_timestamps=predict_timestamps,
  242. **kwargs,
  243. )
  244. if normalizer_file is not None:
  245. with open(normalizer_file, encoding="utf-8") as vocab_handle:
  246. self.english_spelling_normalizer = json.load(vocab_handle)
  247. else:
  248. self.english_spelling_normalizer = None
  249. self.timestamp_pat = re.compile(r"<\|(\d+\.\d+)\|>")
  250. self.language = language
  251. self.task = task
  252. self.predict_timestamps = predict_timestamps
  253. self.set_prefix_tokens()
  254. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._decode_with_timestamps
  255. def _decode_with_timestamps(
  256. self, token_ids, skip_special_tokens=False, time_precision=0.02, segment_size=1500
  257. ) -> str:
  258. """
  259. Timestamp tokens are above the special tokens' id range and are ignored by `decode()`. This method decodes
  260. given tokens with timestamps tokens annotated, e.g. "<|1.08|>".
  261. """
  262. timestamp_begin = self.all_special_ids[-1] + 1
  263. outputs = [[]]
  264. cur_max_timestamp = 0.0
  265. prev_segments_len = 0.0
  266. penultimate_timestamp = 0.0
  267. for i, token in enumerate(token_ids):
  268. if token >= timestamp_begin:
  269. timestamp = float((token - timestamp_begin) * time_precision)
  270. if timestamp < cur_max_timestamp:
  271. # next segment has started
  272. last_was_single_ending = i >= 2 and not (
  273. token_ids[i - 1] >= timestamp_begin and token_ids[i - 2] >= timestamp_begin
  274. )
  275. if last_was_single_ending:
  276. prev_segments_len += time_precision * segment_size
  277. else:
  278. cur_max_timestamp = penultimate_timestamp
  279. prev_segments_len += penultimate_timestamp
  280. outputs = outputs[:-2]
  281. penultimate_timestamp = cur_max_timestamp
  282. cur_max_timestamp = timestamp
  283. outputs.append(f"<|{(timestamp + prev_segments_len):.2f}|>")
  284. outputs.append([])
  285. else:
  286. outputs[-1].append(token)
  287. # Decode token sequences outside list comprehension to avoid super() resolution issues
  288. decoded_outputs = []
  289. for s in outputs:
  290. if isinstance(s, str):
  291. decoded_outputs.append(s)
  292. elif s:
  293. decoded_outputs.append(super().decode(s, skip_special_tokens=skip_special_tokens))
  294. else:
  295. decoded_outputs.append("")
  296. return "".join(decoded_outputs)
  297. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._compute_offsets
  298. def _compute_offsets(self, token_ids, time_precision=0.02, segment_size=1500):
  299. """
  300. Compute offsets for a given tokenized input
  301. Args:
  302. token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
  303. List of tokenized input ids. Can be obtained using the `__call__` method.
  304. time_precision (`float`, *optional*, defaults to 0.02):
  305. The time ratio to convert from token to time.
  306. segment_size (`int`, *optional*, defaults to 1500):
  307. The number of features in the input mel spectrogram.
  308. """
  309. offsets = []
  310. # ensure torch tensor of token ids is placed on cpu
  311. if "torch" in str(type(token_ids)) and (hasattr(token_ids, "cpu") and callable(token_ids.cpu)):
  312. token_ids = token_ids.cpu()
  313. token_ids = np.array(token_ids)
  314. if token_ids.shape[0] > 1 and len(token_ids.shape) > 1:
  315. raise ValueError("Can only process a single input at a time")
  316. timestamp_begin = self.all_special_ids[-1] + 1
  317. timestamp_tokens = token_ids >= timestamp_begin
  318. consecutive = np.where(timestamp_tokens[:-1] & timestamp_tokens[1:])[0] + 1
  319. if consecutive.shape[0] == 0 and timestamp_tokens.sum() <= 1:
  320. # either there are no timestamps or there are no consecutive ones
  321. return []
  322. elif np.where(timestamp_tokens)[0][-1] + 1 not in consecutive:
  323. # we add the final timestamp if it is not already in the list
  324. consecutive = np.append(consecutive, np.where(timestamp_tokens)[0][-1] + 1)
  325. last_slice = np.where(timestamp_tokens)[0][0]
  326. cur_max_timestamp = 0
  327. prev_segments_len = 0
  328. for current_slice in consecutive:
  329. sliced_tokens = token_ids[last_slice:current_slice]
  330. if len(sliced_tokens) > 1:
  331. start_timestamp_position = sliced_tokens[0].item() - timestamp_begin
  332. end_timestamp_position = sliced_tokens[-1].item() - timestamp_begin
  333. if start_timestamp_position < cur_max_timestamp:
  334. # next segment has started
  335. is_single_ending = last_slice >= 2 and not (
  336. token_ids[last_slice - 2] >= timestamp_begin and token_ids[last_slice - 1] >= timestamp_begin
  337. )
  338. if is_single_ending:
  339. prev_segments_len += segment_size
  340. else:
  341. prev_segments_len += cur_max_timestamp
  342. cur_max_timestamp = end_timestamp_position
  343. # strip timestamp tokens from the text output
  344. sliced_tokens = self._preprocess_token_ids(sliced_tokens)
  345. text = self._decode(sliced_tokens)
  346. text = self._filter_timestamp_ids(text)
  347. offsets.append(
  348. {
  349. "text": text,
  350. "timestamp": (
  351. start_timestamp_position * time_precision + prev_segments_len * time_precision,
  352. end_timestamp_position * time_precision + prev_segments_len * time_precision,
  353. ),
  354. }
  355. )
  356. last_slice = current_slice
  357. return offsets
  358. @lru_cache
  359. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.timestamp_ids
  360. def timestamp_ids(self, time_precision=0.02):
  361. """
  362. Compute the timestamp token ids for a given precision and save to least-recently used (LRU) cache.
  363. Args:
  364. time_precision (`float`, *optional*, defaults to 0.02):
  365. The time ratio to convert from token to time.
  366. """
  367. return self.convert_tokens_to_ids([("<|%.2f|>" % (i * time_precision)) for i in range(1500 + 1)])
  368. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._preprocess_token_ids
  369. def _preprocess_token_ids(self, token_ids, skip_special_tokens: bool = False):
  370. """
  371. Pre-process the token ids for decoding by removing the prompt tokens ids and timestamp token ids.
  372. Args:
  373. token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
  374. List of tokenized input ids. Typically, obtained using the `__call__` method of the tokenizer.
  375. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  376. Whether or not to remove special tokens from the token ids. If `True`, the prompt token ids will be
  377. removed.
  378. """
  379. if skip_special_tokens:
  380. prompt_token_id = self.convert_tokens_to_ids("<|startofprev|>")
  381. decoder_start_token_id = self.convert_tokens_to_ids("<|startoftranscript|>")
  382. token_ids = self._strip_prompt(token_ids, prompt_token_id, decoder_start_token_id)
  383. return token_ids
  384. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._filter_timestamp_ids
  385. def _filter_timestamp_ids(self, text):
  386. return re.sub(self.timestamp_pat, "", text)
  387. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.decode
  388. def decode(
  389. self,
  390. token_ids,
  391. skip_special_tokens: bool = False,
  392. clean_up_tokenization_spaces: bool | None = None,
  393. output_offsets: bool = False,
  394. time_precision: float = 0.02,
  395. decode_with_timestamps: bool = False,
  396. normalize: bool = False,
  397. basic_normalize: bool = False,
  398. remove_diacritics: bool = False,
  399. **kwargs,
  400. ) -> str:
  401. """
  402. Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
  403. tokens and clean up tokenization spaces.
  404. Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
  405. Args:
  406. token_ids (`Union[int, list[int], np.ndarray, torch.Tensor]`):
  407. List of tokenized input ids. Can be obtained using the `__call__` method.
  408. skip_special_tokens (`bool`, *optional*, defaults to `False`):
  409. Whether or not to remove special tokens in the decoding. Will remove the previous tokens (pre-prompt)
  410. if present.
  411. clean_up_tokenization_spaces (`bool`, *optional*):
  412. Whether or not to clean up the tokenization spaces. If `None`, will default to
  413. `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
  414. output_offsets (`bool`, *optional*, defaults to `False`):
  415. Whether or not to output the offsets of the tokens. This should only be set if the model predicted
  416. timestamps. If there are previous tokens (pre-prompt) to decode, they will only appear in the decoded
  417. text if they contain timestamp tokens.
  418. time_precision (`float`, *optional*, defaults to 0.02):
  419. The time ratio to convert from token to time.
  420. decode_with_timestamps (`bool`, *optional*, defaults to `False`):
  421. Whether or not to decode with timestamps included in the raw text.
  422. normalize (`bool`, *optional*, defaults to `False`):
  423. Whether or not to apply the English text normalizer to the decoded text. Only applicable when the
  424. target text is in English. Otherwise, the basic text normalizer should be applied.
  425. basic_normalize (`bool`, *optional*, defaults to `False`):
  426. Whether or not to apply the Basic text normalizer to the decoded text. Applicable to multilingual
  427. target text.
  428. remove_diacritics (`bool`, *optional*, defaults to `False`):
  429. Whether or not to remove diacritics when applying the Basic text normalizer. Removing diacritics may
  430. destroy information in the decoded text, hence it should be used with caution.
  431. kwargs (additional keyword arguments, *optional*):
  432. Will be passed to the underlying model specific decode method.
  433. Returns:
  434. `str`: The decoded sentence.
  435. """
  436. filtered_ids = self._preprocess_token_ids(
  437. token_ids,
  438. skip_special_tokens=skip_special_tokens,
  439. )
  440. text = super().decode(
  441. filtered_ids,
  442. skip_special_tokens=skip_special_tokens,
  443. clean_up_tokenization_spaces=clean_up_tokenization_spaces,
  444. normalize=normalize,
  445. basic_normalize=basic_normalize,
  446. remove_diacritics=remove_diacritics,
  447. **kwargs,
  448. )
  449. if decode_with_timestamps:
  450. # legacy method to decode timestamps when not included in the tokenizer vocabulary
  451. text = self._decode_with_timestamps(
  452. filtered_ids, time_precision=time_precision, skip_special_tokens=skip_special_tokens
  453. )
  454. else:
  455. # Handle both single string and batch (list of strings) outputs
  456. if isinstance(text, list):
  457. text = [self._filter_timestamp_ids(t) for t in text]
  458. else:
  459. text = self._filter_timestamp_ids(text)
  460. # retrieve offsets
  461. if output_offsets:
  462. offsets = self._compute_offsets(token_ids, time_precision=time_precision)
  463. return {"text": text, "offsets": offsets}
  464. return text
  465. def _decode(
  466. self, *args, normalize: bool = False, basic_normalize: bool = False, remove_diacritics: bool = False, **kwargs
  467. ) -> str:
  468. text = super()._decode(*args, **kwargs)
  469. if normalize:
  470. clean_text = self.normalize(text)
  471. return clean_text
  472. elif basic_normalize:
  473. clean_text = self.basic_normalize(text, remove_diacritics=remove_diacritics)
  474. return clean_text
  475. else:
  476. return text
  477. def normalize(self, text):
  478. """
  479. Normalize a given string using the `EnglishTextNormalizer` class, which performs commons transformation on
  480. english text.
  481. """
  482. normalizer = EnglishTextNormalizer(self.english_spelling_normalizer)
  483. return normalizer(text)
  484. @staticmethod
  485. def basic_normalize(text, remove_diacritics=False):
  486. """
  487. Normalize a given string using the `BasicTextNormalizer` class, which performs commons transformation on
  488. multilingual text.
  489. """
  490. normalizer = BasicTextNormalizer(remove_diacritics=remove_diacritics)
  491. return normalizer(text)
  492. def save_vocabulary(self, save_directory: str, filename_prefix: str | None = None) -> tuple[str]:
  493. if not os.path.isdir(save_directory):
  494. logger.error(f"Vocabulary path ({save_directory}) should be a directory")
  495. return
  496. vocab_file = os.path.join(
  497. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
  498. )
  499. merge_file = os.path.join(
  500. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
  501. )
  502. normalizer_file = os.path.join(
  503. save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["normalizer_file"]
  504. )
  505. with open(vocab_file, "w", encoding="utf-8") as f:
  506. f.write(json.dumps(self._vocab, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
  507. with open(merge_file, "w", encoding="utf-8") as writer:
  508. writer.write("#version: 0.2\n")
  509. writer.writelines(" ".join(merge_pair) + "\n" for merge_pair in self._merges)
  510. if self.english_spelling_normalizer is not None:
  511. with open(normalizer_file, "w", encoding="utf-8") as f:
  512. f.write(
  513. json.dumps(self.english_spelling_normalizer, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
  514. )
  515. return (vocab_file, merge_file, normalizer_file)
  516. def set_prefix_tokens(
  517. self, language: str | None = None, task: str | None = None, predict_timestamps: bool | None = None
  518. ):
  519. """
  520. Override the prefix tokens appended to the start of the label sequence. This method can be used standalone to
  521. update the prefix tokens as required when fine-tuning. Example:
  522. ```python
  523. >>> # instantiate the tokenizer and set the prefix token to Spanish
  524. >>> tokenizer = WhisperTokenizerFast.from_pretrained("openai/whisper-tiny", language="spanish")
  525. >>> # now switch the prefix token from Spanish to French
  526. >>> tokenizer.set_prefix_tokens(language="french")
  527. ```
  528. Args:
  529. language (`str`, *optional*, defaults to `None`):
  530. The language of the transcription text.
  531. task (`str`, *optional*, defaults to `None`):
  532. Task identifier to append at the start of sequence (if any).
  533. predict_timestamps (`bool`, *optional*, defaults to `None`):
  534. Whether to omit the `<|notimestamps|>` token at the start of the sequence.
  535. """
  536. self.language = language if language is not None else self.language
  537. self.task = task if task is not None else self.task
  538. self.predict_timestamps = predict_timestamps if predict_timestamps is not None else self.predict_timestamps
  539. prefix_token_ids = self.prefix_tokens
  540. prefixes = self.convert_ids_to_tokens(prefix_token_ids)
  541. eos = self.eos_token
  542. eos_token_id = self.eos_token_id
  543. prefix_template = " ".join([f"{token}:0" for token in prefixes])
  544. self.backend_tokenizer.post_processor = processors.TemplateProcessing(
  545. single=f"{prefix_template} $A:0 {eos}:0",
  546. pair=f"{prefix_template} $A:0 $B:1 {eos}:1",
  547. special_tokens=[
  548. (eos, eos_token_id),
  549. *zip(prefixes, prefix_token_ids),
  550. ],
  551. )
  552. @property
  553. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.prefix_tokens
  554. def prefix_tokens(self) -> list[int]:
  555. bos_token_id = self.convert_tokens_to_ids("<|startoftranscript|>")
  556. translate_token_id = self.convert_tokens_to_ids("<|translate|>")
  557. transcribe_token_id = self.convert_tokens_to_ids("<|transcribe|>")
  558. notimestamps_token_id = self.convert_tokens_to_ids("<|notimestamps|>")
  559. langs = tuple(LANGUAGES.keys())
  560. if self.language is not None:
  561. self.language = self.language.lower()
  562. if self.language in TO_LANGUAGE_CODE:
  563. language_id = TO_LANGUAGE_CODE[self.language]
  564. elif self.language in TO_LANGUAGE_CODE.values():
  565. language_id = self.language
  566. else:
  567. is_language_code = len(self.language) == 2
  568. raise ValueError(
  569. f"Unsupported language: {self.language}. Language should be one of:"
  570. f" {list(TO_LANGUAGE_CODE.values()) if is_language_code else list(TO_LANGUAGE_CODE.keys())}."
  571. )
  572. if self.task is not None:
  573. if self.task not in TASK_IDS:
  574. raise ValueError(f"Unsupported task: {self.task}. Task should be in: {TASK_IDS}")
  575. bos_sequence = [bos_token_id]
  576. if self.language is not None:
  577. bos_sequence.append(bos_token_id + 1 + langs.index(language_id))
  578. if self.task is not None:
  579. bos_sequence.append(transcribe_token_id if self.task == "transcribe" else translate_token_id)
  580. if not self.predict_timestamps:
  581. bos_sequence.append(notimestamps_token_id)
  582. return bos_sequence
  583. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.build_inputs_with_special_tokens
  584. def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None) -> list[int]:
  585. """Build model inputs from a sequence by appending eos_token_id."""
  586. if token_ids_1 is None:
  587. return self.prefix_tokens + token_ids_0 + [self.eos_token_id]
  588. # We don't expect to process pairs, but leave the pair logic for API consistency
  589. return self.prefix_tokens + token_ids_0 + token_ids_1 + [self.eos_token_id]
  590. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.get_special_tokens_mask
  591. def get_special_tokens_mask(
  592. self, token_ids_0: list[int], token_ids_1: list[int] | None = None, already_has_special_tokens: bool = False
  593. ) -> list[int]:
  594. """
  595. Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
  596. special tokens using the tokenizer `prepare_for_model` method.
  597. Args:
  598. token_ids_0 (`list[int]`):
  599. List of IDs.
  600. token_ids_1 (`list[int]`, *optional*):
  601. Optional second list of IDs for sequence pairs.
  602. already_has_special_tokens (`bool`, *optional*, defaults to `False`):
  603. Whether or not the token list is already formatted with special tokens for the model.
  604. Returns:
  605. `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
  606. """
  607. if already_has_special_tokens:
  608. return super().get_special_tokens_mask(
  609. token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
  610. )
  611. prefix_ones = [1] * len(self.prefix_tokens)
  612. suffix_ones = [1]
  613. if token_ids_1 is None:
  614. return prefix_ones + ([0] * len(token_ids_0)) + suffix_ones
  615. return prefix_ones + ([0] * len(token_ids_0)) + ([0] * len(token_ids_1)) + suffix_ones
  616. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.get_decoder_prompt_ids
  617. def get_decoder_prompt_ids(self, task=None, language=None, no_timestamps=True):
  618. self.set_prefix_tokens(task=task, language=language, predict_timestamps=not no_timestamps)
  619. # prefix tokens are of the form: <|startoftranscript|> <|lang_id|> <|task|> <|notimestamps|>
  620. # we don't want to force the bos token at position 1, as this is the starting token
  621. # when we generate, so we slice the prefix tokens to: <|lang_id|> <|task|> <|notimestamps|>
  622. # to get the forced tokens
  623. forced_tokens = self.prefix_tokens[1:]
  624. forced_decoder_ids = [(rank + 1, token) for rank, token in enumerate(forced_tokens)]
  625. return forced_decoder_ids
  626. def _decode_asr(self, model_outputs, *, return_timestamps, return_language, time_precision):
  627. return _decode_asr(
  628. self,
  629. model_outputs,
  630. return_timestamps=return_timestamps,
  631. return_language=return_language,
  632. time_precision=time_precision,
  633. )
  634. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer.get_prompt_ids
  635. def get_prompt_ids(self, text: str, return_tensors="np"):
  636. """Converts prompt text to IDs that can be passed to [`~WhisperForConditionalGeneration.generate`]."""
  637. batch_encoding = self("<|startofprev|>", " " + text.strip(), add_special_tokens=False)
  638. # Check for special tokens
  639. prompt_text_ids = batch_encoding["input_ids"][1:]
  640. special_token_id = next((x for x in prompt_text_ids if x >= self.all_special_ids[0]), None)
  641. if special_token_id is not None:
  642. token = self.convert_ids_to_tokens(special_token_id)
  643. raise ValueError(f"Encountered text in the prompt corresponding to disallowed special token: {token}.")
  644. batch_encoding.convert_to_tensors(tensor_type=return_tensors)
  645. return batch_encoding["input_ids"]
  646. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._strip_prompt
  647. def _strip_prompt(self, token_ids: list[int], prompt_token_id: int, decoder_start_token_id: int):
  648. if not isinstance(token_ids, list):
  649. token_ids = self._convert_to_list(token_ids)
  650. # handle case of empty token_ids for decoding with timestamps.
  651. # at this point token_ids is a list, so it is safe to use if not check.
  652. if not token_ids:
  653. return token_ids
  654. has_prompt = token_ids[0] == prompt_token_id
  655. if has_prompt:
  656. if decoder_start_token_id in token_ids:
  657. return token_ids[token_ids.index(decoder_start_token_id) :]
  658. else:
  659. return []
  660. return token_ids
  661. @staticmethod
  662. # Copied from transformers.models.whisper.tokenization_whisper.WhisperTokenizer._convert_to_list
  663. def _convert_to_list(token_ids):
  664. # convert type to ndarray if necessary
  665. if hasattr(token_ids, "numpy"):
  666. token_ids = token_ids.cpu().numpy()
  667. # now the token ids are either a numpy array, or a list of lists
  668. if isinstance(token_ids, np.ndarray):
  669. token_ids = token_ids.tolist()
  670. return token_ids
  671. def _combine_tokens_into_words(
  672. tokenizer,
  673. tokens: list[int],
  674. language: str | None = None,
  675. prepend_punctuations: str = "\"'“¡¿([{-",
  676. append_punctuations: str = "\"'.。,,!!??::”)]}、",
  677. ):
  678. """
  679. Groups tokens by word. Returns a tuple containing a list of strings with the words, and a list of `token_id`
  680. sequences with the tokens making up each word.
  681. """
  682. if language is None:
  683. language = tokenizer.language
  684. if language is None:
  685. language = "english"
  686. if language in {"chinese", "japanese", "thai", "lao", "myanmar", "cantonese"}:
  687. # These languages don't typically use spaces.
  688. words, word_tokens, token_indices = _split_tokens_on_unicode(tokenizer, tokens)
  689. else:
  690. words, word_tokens, token_indices = _split_tokens_on_spaces(tokenizer, tokens)
  691. _merge_punctuations(words, word_tokens, token_indices, prepend_punctuations, append_punctuations)
  692. return words, word_tokens, token_indices
  693. def _find_longest_common_sequence(sequences, token_timestamp_sequences=None):
  694. # It would be much harder to do O(n) because of fault tolerance.
  695. # We actually have a really good property which is that the total sequence
  696. # MUST be those subsequences in order.
  697. # If token_timestamp_sequences is provided, will split those sequences in
  698. # exactly the same way.
  699. left_sequence = sequences[0]
  700. left_length = len(left_sequence)
  701. total_sequence = []
  702. if token_timestamp_sequences:
  703. left_token_timestamp_sequence = token_timestamp_sequences[0]
  704. total_token_timestamp_sequence = []
  705. for seq_idx, right_sequence in enumerate(sequences[1:]):
  706. # index = 0
  707. max_ = 0.0
  708. max_indices = (left_length, left_length, 0, 0)
  709. # Here we're sliding matches
  710. # [a, b, c, d]
  711. # [c, d, f]
  712. # = [c] == [d]
  713. #
  714. # [a, b, c, d]
  715. # [c, d, f]
  716. # = [c, d] == [c, d]
  717. #
  718. #
  719. # [a, b, c, d]
  720. # [c, d, f]
  721. #
  722. # = [b, c, d] == [c, d, f]
  723. #
  724. # [a, b, c, d]
  725. # [c, d, f]
  726. #
  727. # [a, b, c] == [c, d, f]
  728. #
  729. # [a, b, c, d]
  730. # [d, f]
  731. #
  732. # [a, b] == [d, f]
  733. #
  734. # [a, b, c, d]
  735. # [f]
  736. #
  737. # [a] == [f]
  738. right_length = len(right_sequence)
  739. for i in range(1, left_length + right_length):
  740. # epsilon to favor long perfect matches
  741. eps = i / 10000.0
  742. # Slightly convoluted because we don't want out of bound indices
  743. # This will be necessary for a small conflict resolution optimization
  744. # later
  745. left_start = max(0, left_length - i)
  746. left_stop = min(left_length, left_length + right_length - i)
  747. left = np.array(left_sequence[left_start:left_stop])
  748. right_start = max(0, i - left_length)
  749. right_stop = min(right_length, i)
  750. right = np.array(right_sequence[right_start:right_stop])
  751. # We can only match subsequences of the same size.
  752. if len(left) != len(right):
  753. raise RuntimeError(
  754. "There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."
  755. )
  756. if token_timestamp_sequences:
  757. # Get length of longest subsequence of tokens that match
  758. # and have timestamps that are in order
  759. matches = sum(
  760. 1
  761. for idx, elem in enumerate(left)
  762. if (
  763. elem == right[idx]
  764. and left_token_timestamp_sequence[left_start + idx]
  765. <= token_timestamp_sequences[seq_idx + 1][right_start + idx]
  766. )
  767. )
  768. else:
  769. matches = np.sum(left == right)
  770. matching = matches / i + eps
  771. if matches > 1 and matching > max_:
  772. max_ = matching
  773. max_indices = (left_start, left_stop, right_start, right_stop)
  774. (left_start, left_stop, right_start, right_stop) = max_indices
  775. # This is a small conflict optimization since those sequences overlap
  776. # in audio.
  777. # We're going to give more confidence to the left sequence
  778. # for the left of the overlap,
  779. # and to the right of the sequence, for the right of the overlap
  780. left_mid = (left_stop + left_start) // 2
  781. right_mid = (right_stop + right_start) // 2
  782. total_sequence.extend(left_sequence[:left_mid])
  783. left_sequence = right_sequence[right_mid:]
  784. left_length = len(left_sequence)
  785. if token_timestamp_sequences:
  786. total_token_timestamp_sequence.extend(left_token_timestamp_sequence[:left_mid])
  787. left_token_timestamp_sequence = token_timestamp_sequences[seq_idx + 1][right_mid:]
  788. total_sequence.extend(left_sequence)
  789. if token_timestamp_sequences is None:
  790. return total_sequence
  791. if len(token_timestamp_sequences) > 0:
  792. total_token_timestamp_sequence.extend(left_token_timestamp_sequence)
  793. return total_sequence, total_token_timestamp_sequence
  794. else:
  795. return total_sequence, []
  796. def _decode_asr(tokenizer, model_outputs, *, return_timestamps, return_language, time_precision, segment_size=1500):
  797. """
  798. Internal method meant to only be used by asr pipeline. Handles all the little quirks specific to whisper to handle
  799. the various options not allowed in other seq2seq models
  800. """
  801. # =========== Overview ============
  802. # - iterate over all outputs
  803. # - all tokens within output
  804. # - Each token can be
  805. # - language token
  806. # - special token
  807. # - timestamp token
  808. # - text token
  809. # - We accumulate the text tokens.
  810. # - We split on end timestamps
  811. # - Lots of complexity comes from stride and timestamps
  812. last_language = None
  813. def new_chunk():
  814. return {"language": last_language, "timestamp": [None, None], "text": ""}
  815. # Welcome to the state machine !
  816. chunks = []
  817. chunk = new_chunk()
  818. time_offset = 0.0
  819. timestamp_begin = tokenizer.convert_tokens_to_ids("<|notimestamps|>") + 1
  820. previous_tokens = []
  821. previous_token_timestamps = []
  822. skip = False
  823. right_stride_start = None
  824. all_special_ids = set(tokenizer.all_special_ids)
  825. prompt_token_id = tokenizer.convert_tokens_to_ids("<|startofprev|>")
  826. decoder_start_token_id = tokenizer.convert_tokens_to_ids("<|startoftranscript|>")
  827. # - iterate over all outputs
  828. for chunk_id, output in enumerate(model_outputs):
  829. # We can drop everything to Python list, it's going to make
  830. # our lives easier
  831. token_ids = output["tokens"][0].tolist()
  832. # (possibly) remove the prompt from the token ids
  833. token_ids = tokenizer._strip_prompt(token_ids, prompt_token_id, decoder_start_token_id)
  834. if return_timestamps == "word":
  835. token_timestamps = output["token_timestamps"][0].tolist()
  836. # Those keep track of timestamps within strides
  837. # Which need to be skipped and resolve all tokens in a single
  838. # chunk.
  839. last_timestamp = None
  840. first_timestamp = timestamp_begin
  841. # long form generation: we need to handle the case where the call to generate returns concatenated segments,
  842. # with underlying multiple calls to generate
  843. cur_max_timestamp = 0.0
  844. prev_segments_len = 0.0
  845. penultimate_timestamp = 0.0
  846. if "stride" in output:
  847. chunk_len, stride_left, stride_right = output["stride"]
  848. # Offset the timings to account for the other `model_outputs`.
  849. time_offset -= stride_left
  850. right_stride_start = chunk_len - stride_right
  851. # Keeping track of timestamps within strides
  852. # We're going to NOT split on those, and delay until we're
  853. # out of BOTH stride. Otherwise lots of issues occur and
  854. # corner cases
  855. if stride_left:
  856. first_timestamp = stride_left / time_precision + timestamp_begin
  857. if stride_right:
  858. for token in reversed(token_ids):
  859. if token >= timestamp_begin:
  860. # There can be several token in the right stride
  861. # But the last one is ALWAYS going to be skipped
  862. if (
  863. last_timestamp is not None
  864. and (token - timestamp_begin) * time_precision < right_stride_start
  865. ):
  866. break
  867. last_timestamp = token
  868. current_tokens = []
  869. current_token_timestamps = []
  870. # - all tokens within output
  871. for i, token in enumerate(token_ids):
  872. # 4 possible states for each token
  873. # - 1/ Language code
  874. # - 2/ all other special tokens (which we ignore)
  875. # - 3/ Timestamp
  876. # - 4/ Regular text
  877. if token in all_special_ids:
  878. # Either language code or other
  879. text = tokenizer.decode([token])
  880. # Removing outer shell <|XX|>
  881. text = text[2:-2]
  882. language = LANGUAGES.get(text)
  883. if language is not None:
  884. # 1/ Indeed some language
  885. # TODO Handle when language is different from the previous
  886. # one, and we cannot use timestamped tokens to create chunks
  887. if last_language and language != last_language and not return_timestamps:
  888. previous_tokens.append(current_tokens)
  889. resolved_tokens = _find_longest_common_sequence(previous_tokens)
  890. resolved_text = tokenizer.decode(resolved_tokens)
  891. chunk["text"] = resolved_text
  892. chunks.append(chunk)
  893. # Flush all our temporary context
  894. previous_tokens = []
  895. current_tokens = []
  896. chunk = new_chunk()
  897. chunk["language"] = language
  898. last_language = language
  899. else:
  900. # 2/ This is a regular special token, ignoring it
  901. pass
  902. elif token >= timestamp_begin:
  903. # 3/ Timestamp token
  904. timestamp = float((token - timestamp_begin) * time_precision)
  905. if timestamp < cur_max_timestamp:
  906. # next segment has started
  907. last_was_single_ending = i >= 2 and not (
  908. token_ids[i - 1] >= timestamp_begin and token_ids[i - 2] >= timestamp_begin
  909. )
  910. if last_was_single_ending:
  911. prev_segments_len += time_precision * segment_size
  912. else:
  913. cur_max_timestamp = penultimate_timestamp
  914. prev_segments_len += penultimate_timestamp
  915. penultimate_timestamp = cur_max_timestamp
  916. cur_max_timestamp = timestamp
  917. time = (token - timestamp_begin) * time_precision + time_offset + prev_segments_len
  918. time = round(time, 2)
  919. if last_timestamp and token >= last_timestamp:
  920. # Whisper outputted a timestamp token, but it falls within
  921. # our stride, so we're going to skip it for the time being
  922. # and resolve this later
  923. # Skip is necessary because timestamp tokens always come
  924. # by pair, so we need to skip the next one too (which would mark the start of another chunk).
  925. skip = True
  926. elif skip or (previous_tokens and token < first_timestamp):
  927. skip = False
  928. elif chunk["timestamp"][0] is None:
  929. chunk["timestamp"][0] = time
  930. else:
  931. # This is the end of the timestamp chunk
  932. if time == chunk["timestamp"][0]:
  933. # This is a bug in timestamp token output
  934. # where we're taking the duplicate token
  935. # as a stop where it should be a start.
  936. # This is an issue in the underlying model output
  937. # Let's just skip it so it becomes de-factor
  938. # a start again
  939. pass
  940. else:
  941. chunk["timestamp"][1] = time
  942. # Handling merges.
  943. previous_tokens.append(current_tokens)
  944. if return_timestamps == "word":
  945. previous_token_timestamps.append(current_token_timestamps)
  946. resolved_tokens, resolved_token_timestamps = _find_longest_common_sequence(
  947. previous_tokens, previous_token_timestamps
  948. )
  949. resolved_text = tokenizer.decode(resolved_tokens)
  950. chunk["text"] = resolved_text
  951. if return_timestamps == "word":
  952. chunk["words"] = _collate_word_timestamps(
  953. tokenizer, resolved_tokens, resolved_token_timestamps, last_language, return_language
  954. )
  955. chunks.append(chunk)
  956. # Flush all our temporary context
  957. previous_tokens = []
  958. current_tokens = []
  959. previous_token_timestamps = []
  960. current_token_timestamps = []
  961. chunk = new_chunk()
  962. else:
  963. # 4/ Regular token
  964. # We just append to the list of all tokens so we can handle
  965. # merges later and decode into text.
  966. current_tokens.append(token)
  967. if return_timestamps == "word":
  968. if i == 0:
  969. start_time = round(0.0 + time_offset, 2)
  970. else:
  971. start_time = round(token_timestamps[i - 1] + time_offset, 2)
  972. end_time = round(token_timestamps[i] + time_offset, 2)
  973. current_token_timestamps.append((start_time, end_time))
  974. if "stride" in output:
  975. time_offset += chunk_len - stride_right
  976. # Leftover tokens
  977. if current_tokens:
  978. previous_tokens.append(current_tokens)
  979. if return_timestamps == "word":
  980. previous_token_timestamps.append(current_token_timestamps)
  981. elif not (any(p for p in previous_tokens)):
  982. chunk = new_chunk()
  983. previous_tokens = []
  984. current_tokens = []
  985. previous_token_timestamps = []
  986. current_token_timestamps = []
  987. if previous_tokens:
  988. if return_timestamps:
  989. logger.warning(
  990. "Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. "
  991. "Also make sure WhisperTimeStampLogitsProcessor was used during generation."
  992. )
  993. # Happens when we don't use timestamps
  994. resolved_tokens, resolved_token_timestamps = _find_longest_common_sequence(
  995. previous_tokens, previous_token_timestamps
  996. )
  997. resolved_text = tokenizer.decode(resolved_tokens)
  998. chunk["text"] = resolved_text
  999. if return_timestamps == "word":
  1000. chunk["words"] = _collate_word_timestamps(
  1001. tokenizer, resolved_tokens, resolved_token_timestamps, last_language, return_language
  1002. )
  1003. chunks.append(chunk)
  1004. # Preparing and cleaning up the pipeline output
  1005. full_text = "".join(chunk["text"] for chunk in chunks)
  1006. if return_timestamps or return_language:
  1007. for chunk in chunks:
  1008. if not return_timestamps:
  1009. chunk.pop("timestamp")
  1010. else:
  1011. chunk["timestamp"] = tuple(chunk["timestamp"])
  1012. if not return_language:
  1013. chunk.pop("language")
  1014. if return_timestamps == "word":
  1015. new_chunks = []
  1016. for chunk in chunks:
  1017. new_chunks.extend(chunk["words"])
  1018. optional = {"chunks": new_chunks}
  1019. else:
  1020. optional = {"chunks": chunks}
  1021. else:
  1022. optional = {}
  1023. return full_text, optional
  1024. def _find_longest_common_sequence(sequences, token_timestamp_sequences=None):
  1025. # It would be much harder to do O(n) because of fault tolerance.
  1026. # We actually have a really good property which is that the total sequence
  1027. # MUST be those subsequences in order.
  1028. # If token_timestamp_sequences is provided, will split those sequences in
  1029. # exactly the same way.
  1030. left_sequence = sequences[0]
  1031. left_length = len(left_sequence)
  1032. total_sequence = []
  1033. if token_timestamp_sequences:
  1034. left_token_timestamp_sequence = token_timestamp_sequences[0]
  1035. total_token_timestamp_sequence = []
  1036. for seq_idx, right_sequence in enumerate(sequences[1:]):
  1037. # index = 0
  1038. max_ = 0.0
  1039. max_indices = (left_length, left_length, 0, 0)
  1040. # Here we're sliding matches
  1041. # [a, b, c, d]
  1042. # [c, d, f]
  1043. # = [c] == [d]
  1044. #
  1045. # [a, b, c, d]
  1046. # [c, d, f]
  1047. # = [c, d] == [c, d]
  1048. #
  1049. #
  1050. # [a, b, c, d]
  1051. # [c, d, f]
  1052. #
  1053. # = [b, c, d] == [c, d, f]
  1054. #
  1055. # [a, b, c, d]
  1056. # [c, d, f]
  1057. #
  1058. # [a, b, c] == [c, d, f]
  1059. #
  1060. # [a, b, c, d]
  1061. # [d, f]
  1062. #
  1063. # [a, b] == [d, f]
  1064. #
  1065. # [a, b, c, d]
  1066. # [f]
  1067. #
  1068. # [a] == [f]
  1069. right_length = len(right_sequence)
  1070. for i in range(1, left_length + right_length):
  1071. # epsilon to favor long perfect matches
  1072. eps = i / 10000.0
  1073. # Slightly convoluted because we don't want out of bound indices
  1074. # This will be necessary for a small conflict resolution optimization
  1075. # later
  1076. left_start = max(0, left_length - i)
  1077. left_stop = min(left_length, left_length + right_length - i)
  1078. left = np.array(left_sequence[left_start:left_stop])
  1079. right_start = max(0, i - left_length)
  1080. right_stop = min(right_length, i)
  1081. right = np.array(right_sequence[right_start:right_stop])
  1082. # We can only match subsequences of the same size.
  1083. if len(left) != len(right):
  1084. raise RuntimeError(
  1085. "There is a bug within whisper `decode_asr` function, please report it. Dropping to prevent bad inference."
  1086. )
  1087. if token_timestamp_sequences:
  1088. # Get length of longest subsequence of tokens that match
  1089. # and have timestamps that are in order
  1090. matches = sum(
  1091. 1
  1092. for idx, elem in enumerate(left)
  1093. if (
  1094. elem == right[idx]
  1095. and left_token_timestamp_sequence[left_start + idx]
  1096. <= token_timestamp_sequences[seq_idx + 1][right_start + idx]
  1097. )
  1098. )
  1099. else:
  1100. matches = np.sum(left == right)
  1101. matching = matches / i + eps
  1102. if matches > 1 and matching > max_:
  1103. max_ = matching
  1104. max_indices = (left_start, left_stop, right_start, right_stop)
  1105. (left_start, left_stop, right_start, right_stop) = max_indices
  1106. # This is a small conflict optimization since those sequences overlap
  1107. # in audio.
  1108. # We're going to give more confidence to the left sequence
  1109. # for the left of the overlap,
  1110. # and to the right of the sequence, for the right of the overlap
  1111. left_mid = (left_stop + left_start) // 2
  1112. right_mid = (right_stop + right_start) // 2
  1113. total_sequence.extend(left_sequence[:left_mid])
  1114. left_sequence = right_sequence[right_mid:]
  1115. left_length = len(left_sequence)
  1116. if token_timestamp_sequences:
  1117. total_token_timestamp_sequence.extend(left_token_timestamp_sequence[:left_mid])
  1118. left_token_timestamp_sequence = token_timestamp_sequences[seq_idx + 1][right_mid:]
  1119. total_sequence.extend(left_sequence)
  1120. if token_timestamp_sequences is None:
  1121. return total_sequence
  1122. if len(token_timestamp_sequences) > 0:
  1123. total_token_timestamp_sequence.extend(left_token_timestamp_sequence)
  1124. return total_sequence, total_token_timestamp_sequence
  1125. else:
  1126. return total_sequence, []
  1127. def _collate_word_timestamps(tokenizer, tokens, token_timestamps, language, return_language):
  1128. words, _, token_indices = _combine_tokens_into_words(tokenizer, tokens, language)
  1129. optional_language_field = {"language": language} if return_language else {}
  1130. timings = [
  1131. {
  1132. "text": word,
  1133. "timestamp": (token_timestamps[indices[0]][0], token_timestamps[indices[-1]][1]),
  1134. **optional_language_field,
  1135. }
  1136. for word, indices in zip(words, token_indices)
  1137. ]
  1138. return timings
  1139. def _combine_tokens_into_words(
  1140. tokenizer,
  1141. tokens: list[int],
  1142. language: str | None = None,
  1143. prepend_punctuations: str = "\"'“¡¿([{-",
  1144. append_punctuations: str = "\"'.。,,!!??::”)]}、",
  1145. ):
  1146. """
  1147. Groups tokens by word. Returns a tuple containing a list of strings with the words, and a list of `token_id`
  1148. sequences with the tokens making up each word.
  1149. """
  1150. if language is None:
  1151. language = tokenizer.language
  1152. if language is None:
  1153. language = "english"
  1154. if language in {"chinese", "japanese", "thai", "lao", "myanmar", "cantonese"}:
  1155. # These languages don't typically use spaces.
  1156. words, word_tokens, token_indices = _split_tokens_on_unicode(tokenizer, tokens)
  1157. else:
  1158. words, word_tokens, token_indices = _split_tokens_on_spaces(tokenizer, tokens)
  1159. _merge_punctuations(words, word_tokens, token_indices, prepend_punctuations, append_punctuations)
  1160. return words, word_tokens, token_indices
  1161. def _split_tokens_on_unicode(tokenizer, tokens: list[int]):
  1162. """Combine tokens into words by splitting at any position where the tokens are decoded as valid unicode points."""
  1163. decoded_full = tokenizer.decode(tokens, decode_with_timestamps=True)
  1164. replacement_char = "\ufffd"
  1165. words = []
  1166. word_tokens = []
  1167. token_indices = []
  1168. current_tokens = []
  1169. current_indices = []
  1170. unicode_offset = 0
  1171. for token_idx, token in enumerate(tokens):
  1172. current_tokens.append(token)
  1173. current_indices.append(token_idx)
  1174. decoded = tokenizer.decode(current_tokens, decode_with_timestamps=True)
  1175. if (
  1176. replacement_char not in decoded
  1177. or decoded_full[unicode_offset + decoded.index(replacement_char)] == replacement_char
  1178. ):
  1179. words.append(decoded)
  1180. word_tokens.append(current_tokens)
  1181. token_indices.append(current_indices)
  1182. current_tokens = []
  1183. current_indices = []
  1184. unicode_offset += len(decoded)
  1185. return words, word_tokens, token_indices
  1186. def _split_tokens_on_spaces(tokenizer, tokens: list[int]):
  1187. """Combine tokens into words by splitting at whitespace and punctuation tokens."""
  1188. subwords, subword_tokens_list, subword_indices_list = _split_tokens_on_unicode(tokenizer, tokens)
  1189. words = []
  1190. word_tokens = []
  1191. token_indices = []
  1192. for subword, subword_tokens, subword_indices in zip(subwords, subword_tokens_list, subword_indices_list):
  1193. special = subword_tokens[0] >= tokenizer.eos_token_id
  1194. with_space = subword.startswith(" ")
  1195. punctuation = subword.strip() in "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
  1196. if special or with_space or punctuation or len(words) == 0:
  1197. words.append(subword)
  1198. word_tokens.append(subword_tokens)
  1199. token_indices.append(subword_indices)
  1200. else:
  1201. words[-1] = words[-1] + subword
  1202. word_tokens[-1].extend(subword_tokens)
  1203. token_indices[-1].extend(subword_indices)
  1204. return words, word_tokens, token_indices
  1205. def _merge_punctuations(words, tokens, indices, prepended, appended):
  1206. """Merges punctuation tokens with neighboring words."""
  1207. # prepend punctuations
  1208. i = len(words) - 2
  1209. j = len(words) - 1
  1210. while i >= 0:
  1211. if words[i].startswith(" ") and words[i].strip() in prepended:
  1212. words[j] = words[i] + words[j]
  1213. tokens[j] = tokens[i] + tokens[j]
  1214. indices[j] = indices[i] + indices[j]
  1215. words[i] = ""
  1216. tokens[i] = []
  1217. indices[i] = []
  1218. else:
  1219. j = i
  1220. i -= 1
  1221. # append punctuations
  1222. i = 0
  1223. j = 1
  1224. while j < len(words):
  1225. if not words[i].endswith(" ") and words[j] in appended:
  1226. words[i] += words[j]
  1227. tokens[i] += tokens[j]
  1228. indices[i] += indices[j]
  1229. words[j] = ""
  1230. tokens[j] = []
  1231. indices[j] = []
  1232. else:
  1233. i = j
  1234. j += 1
  1235. # remove elements that are now empty
  1236. words[:] = [word for word in words if word]
  1237. tokens[:] = [token for token in tokens if token]
  1238. indices[:] = [idx for idx in indices if idx]
  1239. __all__ = ["WhisperTokenizer"]