codingutf8 2021 the facebook inc and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license tokenization class for wav2vec2phoneme import json import os import sys from dataclasses import dataclass from itertools import groupby from typing import typechecking any dict list optional tuple union import numpy as np from tokenizationutils import pretrainedtokenizer from tokenizationutilsbase import addedtoken from utils import modeloutput isflaxavailable istfavailable istorchavailable logging requiresbackends topyobj logger logging getloggername if typechecking if istorchavailable import torch if istfavailable import tensorflow as tf if isflaxavailable import jax numpy as jnp noqa f401 vocabfilesnames vocabfile vocab json tokenizerconfigfile tokenizerconfig json pretrainedvocabfilesmap vocabfile facebookwav2vec2lv60espeakcvft https huggingface cofacebookwav2vec2lv60espeakcvftresolvemainvocab json tokenizerconfigfile facebookwav2vec2lv60espeakcvft https huggingface cofacebookwav2vec2lv60espeakcvftresolvemaintokenizerconfig json wav2vec2phoneme has no max input length pretrainedpositionalembeddingssizes facebookwav2vec2lv60espeakcvft sys maxsize listofdict listdictstr unionint str dataclass class wav2vec2phonemectctokenizeroutputmodeloutput text unionliststr str charoffsets unionlistlistofdict listofdict none class wav2vec2phonemectctokenizerpretrainedtokenizer vocabfilesnames vocabfilesnames pretrainedvocabfilesmap pretrainedvocabfilesmap maxmodelinputsizes pretrainedpositionalembeddingssizes modelinputnames inputids attentionmask def init self vocabfile bostokens eostokens unktokenunk padtokenpad phonedelimitertoken worddelimitertokennone dophonemizetrue phonemizerlangenus phonemizerbackendespeak kwargs self worddelimitertoken worddelimitertoken self phonedelimitertoken phonedelimitertoken self dophonemize dophonemize self phonemizerlang phonemizerlang self phonemizerbackend phonemizerbackend if dophonemize self initbackendself phonemizerlang with openvocabfile encodingutf8 as vocabhandle self encoder json loadvocabhandle self decoder v k for k v in self encoder items super init unktokenunktoken bostokenbostoken eostokeneostoken padtokenpadtoken worddelimitertokenworddelimitertoken phonedelimitertokenphonedelimitertoken dophonemizedophonemize phonemizerlangphonemizerlang phonemizerbackendphonemizerbackend kwargs property def vocabsizeself int return lenself decoder def getvocabself dict vocab dictself encoder copy vocab updateself addedtokensencoder return vocab def addtokensself newtokens unionliststr listaddedtoken specialtokens bool false int overwritten to never strip toadd for token in newtokens if isinstancetoken str toadd appendaddedtokentoken rstripfalse lstripfalse normalizedtrue specialspecialtokens else toadd appendtoken return super addtokenstoadd specialtokens def initbackendself phonemizerlang str requiresbackendsself phonemizer from phonemizer backend import backends self backend backendsself phonemizerbackendphonemizerlang languageswitchremoveflags def preparefortokenization self text str issplitintowords bool false phonemizerlang optionalstr none dophonemize optionalbool none tuplestr dictstr any if issplitintowords text text set whether tokenizer should phonemize or not if dophonemize is not none self dophonemize dophonemize set the correct phonemizer language if phonemizerlang is not none self phonemizerlang phonemizerlang self initbackendphonemizerlang return text def tokenizeself text kwargs make sure whitespace is stripped to prevent unk text text strip phonemize if self dophonemize text text lower create list of phonemes text self phonemizetext self phonemizerlang make sure is between phonemes tokens text split tokens listfilterlambda p p strip tokens return tokens def phonemizeself text str phonemizerlang optionalstr none str from phonemizer separator import separator worddelimiter self worddelimitertoken if self worddelimitertoken is not none else if phonemizerlang is not none and phonemizerlang self phonemizerlang self initbackendphonemizerlang else phonemizerlang self phonemizerlang separator separatorphoneself phonedelimitertoken wordworddelimiter syllable phonemes self backend phonemize text separatorseparator phonemes phonemes0 strip return phonemes property def worddelimitertokenself str if self worddelimitertoken is none if self verbose logger errorusing worddelimitertoken but it is not set yet return none return strself worddelimitertoken property def worddelimitertokenidself optionalint if self worddelimitertoken is none return none return self converttokenstoidsself worddelimitertoken worddelimitertoken setter def worddelimitertokenself value self worddelimitertoken value worddelimitertokenid setter def worddelimitertokenidself value self worddelimitertoken self converttokenstoidsvalue property def phonedelimitertokenself str if self phonedelimitertoken is none if self verbose logger errorusing phonedelimitertoken but it is not set yet return none return strself phonedelimitertoken property def phonedelimitertokenidself optionalint if self phonedelimitertoken is none return none return self converttokenstoidsself phonedelimitertoken phonedelimitertoken setter def phonedelimitertokenself value self phonedelimitertoken value phonedelimitertokenid setter def phonedelimitertokenidself value self phonedelimitertoken self converttokenstoidsvalue def converttokentoidself token str int converts an index integer in a token str using the vocab result self decoder getindex self unktoken return result def converttokenstostring self tokens liststr grouptokens bool true spacesbetweenspecialtokens bool false filterworddelimitertoken bool true outputcharoffsets bool false str group same tokens into nonrepeating tokens in ctc style decoding if grouptokens chars charrepetitions ziptoken lenlistgroupiter for token groupiter in groupbytokens else chars tokens charrepetitions lentokens 1 filter self padtoken which is used as ctcblank token processedchars listfilterlambda char char self padtoken chars also filter self worddelimitertoken if not not if filterworddelimitertoken and self worddelimitertoken is not none processedchars listfilterlambda token token self worddelimitertoken processedchars retrieve offsets charoffsets none if outputcharoffsets worddelimitertokenforoffsets self worddelimitertoken if filterworddelimitertoken is true else none charoffsets self computeoffsets charrepetitions chars self padtoken worddelimitertokenworddelimitertokenforoffsets if lencharoffsets lenprocessedchars raise valueerror fcharoffsets charoffsets and processedtokens processedchars have to be of the same length but are lenoffsets flencharoffsets and lenprocessedtokens lenprocessedchars set tokens to correct processed token for i char in enumerateprocessedchars charoffsetsichar char string joinprocessedchars strip return text string charoffsets charoffsets staticmethod def computeoffsets charrepetitions listint chars liststr ctctoken int worddelimitertoken optionalint none listdictstr unionstr int endindices np asarraycharrepetitions cumsum startindices np concatenate0 endindices 1 offsets char t startoffset s endoffset e for t s e in zipchars startindices endindices filter out ctc token offsets listfilterlambda offsets offsetschar ctctoken offsets filter out word delimiter token if necessary if worddelimitertoken is not none offsets listfilterlambda offsets offsetschar worddelimitertoken offsets return offsets def decode self tokenids listint skipspecialtokens bool false cleanuptokenizationspaces bool none grouptokens bool true filterworddelimitertoken bool true spacesbetweenspecialtokens bool false outputcharoffsets bool false str filteredtokens self convertidstotokenstokenids skipspecialtokensskipspecialtokens result for token in filteredtokens if skipspecialtokens and token in self allspecialids continue result appendtoken stringoutput self converttokenstostring result grouptokensgrouptokens spacesbetweenspecialtokensspacesbetweenspecialtokens filterworddelimitertokenfilterworddelimitertoken outputcharoffsetsoutputcharoffsets text stringoutputtext cleanuptokenizationspaces cleanuptokenizationspaces if cleanuptokenizationspaces is not none else self cleanuptokenizationspaces if cleanuptokenizationspaces text self cleanuptokenizationtext if outputcharoffsets return wav2vec2phonemectctokenizeroutputtexttext charoffsetsstringoutputcharoffsets else return text overwritten from tokenizationutilsbase py because we need docs for outputcharoffsets here def decode self tokenids unionint listint np ndarray torch tensor tf tensor skipspecialtokens bool false cleanuptokenizationspaces bool none outputcharoffsets bool false kwargs str convert inputs to python lists tokenids topyobjtokenids return self decode tokenidstokenids skipspecialtokensskipspecialtokens cleanuptokenizationspacescleanuptokenizationspaces outputcharoffsetsoutputcharoffsets kwargs overwritten from tokenizationutilsbase py because tokenizer can output modeloutput which should not be a list for batched output and because we need docs for outputcharoffsets here def batchdecode self sequences unionlistint listlistint np ndarray torch tensor tf tensor skipspecialtokens bool false cleanuptokenizationspaces bool none outputcharoffsets bool false kwargs liststr batchdecoded self decode seq skipspecialtokensskipspecialtokens cleanuptokenizationspacescleanuptokenizationspaces outputcharoffsetsoutputcharoffsets kwargs for seq in sequences if outputcharoffsets transform list of dicts to dict of lists return wav2vec2phonemectctokenizeroutputk dk for d in batchdecoded for k in batchdecoded0 return batchdecoded def savevocabularyself savedirectory str filenameprefix optionalstr none tuplestr if not os path isdirsavedirectory logger errorfvocabulary path savedirectory should be a directory return vocabfile os path join savedirectory filenameprefix if filenameprefix else vocabfilesnamesvocabfile with openvocabfile w encodingutf8 as f f writejson dumpsself encoder indent2 sortkeystrue ensureasciifalse n return vocabfile coding utf 8 2021 the facebook inc and the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license tokenization class for wav2vec2phoneme noqa f401 wav2vec2phoneme has no max input length output type of wav2vec2phonemectctokenizer with transcription args text list of str or str decoded logits in text from usually the speech transcription char_offsets list of list dict str union int str or list dict str union int str offsets of the decoded characters in combination with sampling rate and model downsampling rate char offsets can be used to compute time stamps for each charater total logit score of the beam associated with produced text constructs a wav2vec2phonemectc tokenizer this tokenizer inherits from pretrainedtokenizer which contains some of the main methods users should refer to the superclass for more information regarding such methods args vocab_file str file containing the vocabulary bos_token str optional defaults to s the beginning of sentence token eos_token str optional defaults to s the end of sentence token unk_token str optional defaults to unk 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 pad_token str optional defaults to pad the token used for padding for example when batching sequences of different lengths do_phonemize bool optional defaults to true whether the tokenizer should phonetize the input or not only if a sequence of phonemes is passed to the tokenizer do_phonemize should be set to false phonemizer_lang str optional defaults to en us the language of the phoneme set to which the tokenizer should phonetize the input text to phonemizer_backend str optional defaults to espeak the backend phonetization library that shall be used by the phonemizer library defaults to espeak ng see the phonemizer package https github com bootphon phonemizer readme for more information kwargs additional keyword arguments passed along to pretrainedtokenizer overwritten to never strip initializes the backend args phonemizer_lang str the language to be used performs any necessary transformations before tokenization this method should pop the arguments from kwargs and return the remaining kwargs as well we test the kwargs at the end of the encoding process to be sure all the arguments have been used args text str the text to prepare is_split_into_words bool optional defaults to false whether or not the input is already pre tokenized e g split into words if set to true the tokenizer assumes the input is already split into words for instance by splitting it on whitespace which it will tokenize this is useful for ner or token classification phonemizer_lang str optional the language of the phoneme set to which the tokenizer should phonetize the input text to do_phonemize bool optional whether the tokenizer should phonetize the input text or not only if a sequence of phonemes is passed to the tokenizer do_phonemize should be set to false returns tuple str dict str any the prepared text and the unused kwargs set whether tokenizer should phonemize or not set the correct phonemizer language converts a string in a sequence of tokens string using the tokenizer make sure whitespace is stripped to prevent unk phonemize create list of phonemes make sure is between phonemes str word delimiter token log an error if used while not having been set optional int id of the word_delimiter_token in the vocabulary returns none if the token has not been set str word delimiter token log an error if used while not having been set optional int id of the phone_delimiter_token in the vocabulary returns none if the token has not been set converts a token str in an index integer using the vocab converts an index integer in a token str using the vocab converts a connectionist temporal classification ctc output tokens into a single string group same tokens into non repeating tokens in ctc style decoding filter self pad_token which is used as ctc blank token also filter self word_delimiter_token if not not retrieve offsets set tokens to correct processed token filter out ctc token filter out word delimiter token if necessary special _decode function is needed for wav2vec2phonemetokenizer because added tokens should be treated exactly the same as tokens of the base vocabulary and therefore the function convert_tokens_to_string has to be called on the whole token list and not individually on added tokens overwritten from tokenization_utils_base py because we need docs for output_char_offsets here converts a sequence of ids in a string using the tokenizer and vocabulary with options to remove special tokens and clean up tokenization spaces similar to doing self convert_tokens_to_string self convert_ids_to_tokens token_ids args token_ids union int list int np ndarray torch tensor tf tensor list of tokenized input ids can be obtained using the __call__ method skip_special_tokens bool optional defaults to false whether or not to remove special tokens in the decoding clean_up_tokenization_spaces bool optional whether or not to clean up the tokenization spaces output_char_offsets bool optional defaults to false whether or not to output character offsets character offsets can be used in combination with the sampling rate and model downsampling rate to compute the time stamps of transcribed characters tip please take a look at the example of models wav2vec2 tokenization_wav2vec2 decode to better understand how to make use of output_word_offsets model wav2vec2_phoneme tokenization_wav2vec2_phoneme batch_decode works the same way with phonemes tip kwargs additional keyword arguments optional will be passed to the underlying model specific decode method returns str or models wav2vec2 tokenization_wav2vec2_phoneme wav2vec2phonemectctokenizeroutput the decoded sentence will be a models wav2vec2 tokenization_wav2vec2_phoneme wav2vec2phonemectctokenizeroutput when output_char_offsets true convert inputs to python lists overwritten from tokenization_utils_base py because tokenizer can output modeloutput which should not be a list for batched output and because we need docs for output_char_offsets here convert a list of lists of token ids into a list of strings by calling decode args sequences union list int list list int np ndarray torch tensor tf tensor list of tokenized input ids can be obtained using the __call__ method skip_special_tokens bool optional defaults to false whether or not to remove special tokens in the decoding clean_up_tokenization_spaces bool optional whether or not to clean up the tokenization spaces output_char_offsets bool optional defaults to false whether or not to output character offsets character offsets can be used in combination with the sampling rate and model downsampling rate to compute the time stamps of transcribed characters tip please take a look at the example of models wav2vec2 tokenization_wav2vec2 decode to better understand how to make use of output_word_offsets model wav2vec2_phoneme tokenization_wav2vec2_phoneme batch_decode works analogous with phonemes and batched output tip kwargs additional keyword arguments optional will be passed to the underlying model specific decode method returns list str or models wav2vec2 tokenization_wav2vec2_phoneme wav2vec2phonemectctokenizeroutput the decoded sentence will be a models wav2vec2 tokenization_wav2vec2_phoneme wav2vec2phonemectctokenizeroutput when output_char_offsets true transform list of dicts to dict of lists
import json
import os
import sys
from dataclasses import dataclass
from itertools import groupby
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import numpy as np

from ...tokenization_utils import PreTrainedTokenizer
from ...tokenization_utils_base import AddedToken
from ...utils import (
    ModelOutput,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    logging,
    requires_backends,
    to_py_obj,
)


logger = logging.get_logger(__name__)


if TYPE_CHECKING:
    if is_torch_available():
        import torch
    if is_tf_available():
        import tensorflow as tf
    if is_flax_available():
        import jax.numpy as jnp  


VOCAB_FILES_NAMES = {
    "vocab_file": "vocab.json",
    "tokenizer_config_file": "tokenizer_config.json",
}

PRETRAINED_VOCAB_FILES_MAP = {
    "vocab_file": {
        "facebook/wav2vec2-lv-60-espeak-cv-ft": (
            "https://huggingface.co/facebook/wav2vec2-lv-60-espeak-cv-ft/resolve/main/vocab.json"
        ),
    },
    "tokenizer_config_file": {
        "facebook/wav2vec2-lv-60-espeak-cv-ft": (
            "https://huggingface.co/facebook/wav2vec2-lv-60-espeak-cv-ft/resolve/main/tokenizer_config.json"
        ),
    },
}


PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {"facebook/wav2vec2-lv-60-espeak-cv-ft": sys.maxsize}


ListOfDict = List[Dict[str, Union[int, str]]]


@dataclass
class Wav2Vec2PhonemeCTCTokenizerOutput(ModelOutput):
    

    text: Union[List[str], str]
    char_offsets: Union[List[ListOfDict], ListOfDict] = None


class Wav2Vec2PhonemeCTCTokenizer(PreTrainedTokenizer):

    

    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        bos_token="<s>",
        eos_token="</s>",
        unk_token="<unk>",
        pad_token="<pad>",
        phone_delimiter_token=" ",
        word_delimiter_token=None,
        do_phonemize=True,
        phonemizer_lang="en-us",
        phonemizer_backend="espeak",
        **kwargs,
    ):
        self._word_delimiter_token = word_delimiter_token
        self._phone_delimiter_token = phone_delimiter_token
        self.do_phonemize = do_phonemize
        self.phonemizer_lang = phonemizer_lang
        self.phonemizer_backend = phonemizer_backend

        if do_phonemize:
            self.init_backend(self.phonemizer_lang)

        with open(vocab_file, encoding="utf-8") as vocab_handle:
            self.encoder = json.load(vocab_handle)
        self.decoder = {v: k for k, v in self.encoder.items()}

        super().__init__(
            unk_token=unk_token,
            bos_token=bos_token,
            eos_token=eos_token,
            pad_token=pad_token,
            word_delimiter_token=word_delimiter_token,
            phone_delimiter_token=phone_delimiter_token,
            do_phonemize=do_phonemize,
            phonemizer_lang=phonemizer_lang,
            phonemizer_backend=phonemizer_backend,
            **kwargs,
        )

    @property
    def vocab_size(self) -> int:
        return len(self.decoder)

    def get_vocab(self) -> Dict:
        vocab = dict(self.encoder.copy())
        vocab.update(self.added_tokens_encoder)
        return vocab

    def _add_tokens(self, new_tokens: Union[List[str], List[AddedToken]], special_tokens: bool = False) -> int:
        
        to_add = []
        for token in new_tokens:
            if isinstance(token, str):
                to_add.append(AddedToken(token, rstrip=False, lstrip=False, normalized=True, special=special_tokens))
            else:
                to_add.append(token)

        return super()._add_tokens(to_add, special_tokens)

    def init_backend(self, phonemizer_lang: str):
        
        requires_backends(self, "phonemizer")
        from phonemizer.backend import BACKENDS

        self.backend = BACKENDS[self.phonemizer_backend](phonemizer_lang, language_switch="remove-flags")

    def prepare_for_tokenization(
        self,
        text: str,
        is_split_into_words: bool = False,
        phonemizer_lang: Optional[str] = None,
        do_phonemize: Optional[bool] = None,
    ) -> Tuple[str, Dict[str, Any]]:
        
        if is_split_into_words:
            text = " " + text

        
        if do_phonemize is not None:
            self.do_phonemize = do_phonemize

        
        if phonemizer_lang is not None:
            self.phonemizer_lang = phonemizer_lang
            self.init_backend(phonemizer_lang)

        return (text, {})

    def _tokenize(self, text, **kwargs):
        

        
        text = text.strip()

        
        if self.do_phonemize:
            text = text.lower()

            
            text = self.phonemize(text, self.phonemizer_lang)

        
        tokens = text.split(" ")

        tokens = list(filter(lambda p: p.strip() != "", tokens))
        return tokens

    def phonemize(self, text: str, phonemizer_lang: Optional[str] = None) -> str:
        from phonemizer.separator import Separator

        word_delimiter = self.word_delimiter_token + " " if self.word_delimiter_token is not None else ""
        if phonemizer_lang is not None and phonemizer_lang != self.phonemizer_lang:
            self.init_backend(phonemizer_lang)
        else:
            phonemizer_lang = self.phonemizer_lang

        separator = Separator(phone=self.phone_delimiter_token, word=word_delimiter, syllable="")
        phonemes = self.backend.phonemize(
            [text],
            separator=separator,
        )
        phonemes = phonemes[0].strip()

        return phonemes

    @property
    def word_delimiter_token(self) -> str:
        
        if self._word_delimiter_token is None:
            if self.verbose:
                logger.error("Using word_delimiter_token, but it is not set yet.")
            return None
        return str(self._word_delimiter_token)

    @property
    def word_delimiter_token_id(self) -> Optional[int]:
        
        if self._word_delimiter_token is None:
            return None
        return self.convert_tokens_to_ids(self.word_delimiter_token)

    @word_delimiter_token.setter
    def word_delimiter_token(self, value):
        self._word_delimiter_token = value

    @word_delimiter_token_id.setter
    def word_delimiter_token_id(self, value):
        self._word_delimiter_token = self.convert_tokens_to_ids(value)

    @property
    def phone_delimiter_token(self) -> str:
        
        if self._phone_delimiter_token is None:
            if self.verbose:
                logger.error("Using phone_delimiter_token, but it is not set yet.")
            return None
        return str(self._phone_delimiter_token)

    @property
    def phone_delimiter_token_id(self) -> Optional[int]:
        
        if self._phone_delimiter_token is None:
            return None
        return self.convert_tokens_to_ids(self.phone_delimiter_token)

    @phone_delimiter_token.setter
    def phone_delimiter_token(self, value):
        self._phone_delimiter_token = value

    @phone_delimiter_token_id.setter
    def phone_delimiter_token_id(self, value):
        self._phone_delimiter_token = self.convert_tokens_to_ids(value)

    def _convert_token_to_id(self, token: str) -> int:
        
        return self.encoder.get(token, self.encoder.get(self.unk_token))

    def _convert_id_to_token(self, index: int) -> str:
        
        result = self.decoder.get(index, self.unk_token)
        return result

    def convert_tokens_to_string(
        self,
        tokens: List[str],
        group_tokens: bool = True,
        spaces_between_special_tokens: bool = False,
        filter_word_delimiter_token: bool = True,
        output_char_offsets: bool = False,
    ) -> str:
        
        
        if group_tokens:
            chars, char_repetitions = zip(*((token, len(list(group_iter))) for token, group_iter in groupby(tokens)))
        else:
            chars = tokens
            char_repetitions = len(tokens) * [1]

        
        processed_chars = list(filter(lambda char: char != self.pad_token, chars))

        
        if filter_word_delimiter_token and self.word_delimiter_token is not None:
            processed_chars = list(filter(lambda token: token != self.word_delimiter_token, processed_chars))

        
        char_offsets = None
        if output_char_offsets:
            word_delimiter_token_for_offsets = (
                self.word_delimiter_token if filter_word_delimiter_token is True else None
            )
            char_offsets = self._compute_offsets(
                char_repetitions, chars, self.pad_token, word_delimiter_token=word_delimiter_token_for_offsets
            )

            if len(char_offsets) != len(processed_chars):
                raise ValueError(
                    f"`char_offsets`: {char_offsets} and `processed_tokens`: {processed_chars}"
                    " have to be of the same length, but are: `len(offsets)`: "
                    f"{len(char_offsets)} and `len(processed_tokens)`: {len(processed_chars)}"
                )

            
            for i, char in enumerate(processed_chars):
                char_offsets[i]["char"] = char

        string = " ".join(processed_chars).strip()

        return {"text": string, "char_offsets": char_offsets}

    @staticmethod
    def _compute_offsets(
        char_repetitions: List[int], chars: List[str], ctc_token: int, word_delimiter_token: Optional[int] = None
    ) -> List[Dict[str, Union[str, int]]]:
        end_indices = np.asarray(char_repetitions).cumsum()
        start_indices = np.concatenate(([0], end_indices[:-1]))

        offsets = [
            {"char": t, "start_offset": s, "end_offset": e} for t, s, e in zip(chars, start_indices, end_indices)
        ]

        
        offsets = list(filter(lambda offsets: offsets["char"] != ctc_token, offsets))

        
        if word_delimiter_token is not None:
            offsets = list(filter(lambda offsets: offsets["char"] != word_delimiter_token, offsets))

        return offsets

    def _decode(
        self,
        token_ids: List[int],
        skip_special_tokens: bool = False,
        clean_up_tokenization_spaces: bool = None,
        group_tokens: bool = True,
        filter_word_delimiter_token: bool = True,
        spaces_between_special_tokens: bool = False,
        output_char_offsets: bool = False,
    ) -> str:
        
        filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)

        result = []
        for token in filtered_tokens:
            if skip_special_tokens and token in self.all_special_ids:
                continue
            result.append(token)

        string_output = self.convert_tokens_to_string(
            result,
            group_tokens=group_tokens,
            spaces_between_special_tokens=spaces_between_special_tokens,
            filter_word_delimiter_token=filter_word_delimiter_token,
            output_char_offsets=output_char_offsets,
        )

        text = string_output["text"]

        clean_up_tokenization_spaces = (
            clean_up_tokenization_spaces
            if clean_up_tokenization_spaces is not None
            else self.clean_up_tokenization_spaces
        )
        if clean_up_tokenization_spaces:
            text = self.clean_up_tokenization(text)

        if output_char_offsets:
            return Wav2Vec2PhonemeCTCTokenizerOutput(text=text, char_offsets=string_output["char_offsets"])
        else:
            return text

    
    def decode(
        self,
        token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
        skip_special_tokens: bool = False,
        clean_up_tokenization_spaces: bool = None,
        output_char_offsets: bool = False,
        **kwargs,
    ) -> str:
        
        
        token_ids = to_py_obj(token_ids)

        return self._decode(
            token_ids=token_ids,
            skip_special_tokens=skip_special_tokens,
            clean_up_tokenization_spaces=clean_up_tokenization_spaces,
            output_char_offsets=output_char_offsets,
            **kwargs,
        )

    
    
    
    def batch_decode(
        self,
        sequences: Union[List[int], List[List[int]], "np.ndarray", "torch.Tensor", "tf.Tensor"],
        skip_special_tokens: bool = False,
        clean_up_tokenization_spaces: bool = None,
        output_char_offsets: bool = False,
        **kwargs,
    ) -> List[str]:
        
        batch_decoded = [
            self.decode(
                seq,
                skip_special_tokens=skip_special_tokens,
                clean_up_tokenization_spaces=clean_up_tokenization_spaces,
                output_char_offsets=output_char_offsets,
                **kwargs,
            )
            for seq in sequences
        ]
        if output_char_offsets:
            
            return Wav2Vec2PhonemeCTCTokenizerOutput({k: [d[k] for d in batch_decoded] for k in batch_decoded[0]})

        return batch_decoded

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )

        with open(vocab_file, "w", encoding="utf-8") as f:
            f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

        return (vocab_file,)