You need to sign in or sign up before continuing.
text_featurizer.py 6.3 KB
Newer Older
H
Hui Zhang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
14
"""Contains the text featurizer class."""
15
import sentencepiece as spm
16

17 18
from ..utility import EOS
from ..utility import load_dict
H
Hui Zhang 已提交
19
from ..utility import SPACE
20
from ..utility import UNK
21

22
__all__ = ["TextFeaturizer"]
23

24 25 26 27 28 29 30

class TextFeaturizer():
    def __init__(self,
                 unit_type,
                 vocab_filepath,
                 spm_model_prefix=None,
                 maskctc=False):
31
        """Text featurizer, for processing or extracting features from text.
32

33 34 35
        Currently, it supports char/word/sentence-piece level tokenizing and conversion into
        a list of token indices. Note that the token indexing order follows the
        given vocabulary file.
36

37 38 39 40 41 42 43 44
        Args:
            unit_type (str): unit type, e.g. char, word, spm
            vocab_filepath (str): Filepath to load vocabulary for token indices conversion.
            spm_model_prefix (str, optional): spm model prefix. Defaults to None.
        """
        assert unit_type in ('char', 'spm', 'word')
        self.unit_type = unit_type
        self.unk = UNK
45 46
        self.maskctc = maskctc

47
        if vocab_filepath:
48 49 50
            self.vocab_dict, self._id2token, self.vocab_list, self.unk_id, self.eos_id = self._load_vocabulary_from_file(
                vocab_filepath, maskctc)
            self.vocab_size = len(self.vocab_list)
51 52 53 54 55 56

        if unit_type == 'spm':
            spm_model = spm_model_prefix + '.model'
            self.sp = spm.SentencePieceProcessor()
            self.sp.Load(spm_model)

H
Hui Zhang 已提交
57
    def tokenize(self, text, replace_space=True):
58
        if self.unit_type == 'char':
H
Hui Zhang 已提交
59
            tokens = self.char_tokenize(text, replace_space)
60 61 62 63 64
        elif self.unit_type == 'word':
            tokens = self.word_tokenize(text)
        else:  # spm
            tokens = self.spm_tokenize(text)
        return tokens
65

66 67 68 69 70 71 72 73
    def detokenize(self, tokens):
        if self.unit_type == 'char':
            text = self.char_detokenize(tokens)
        elif self.unit_type == 'word':
            text = self.word_detokenize(tokens)
        else:  # spm
            text = self.spm_detokenize(tokens)
        return text
74

75
    def featurize(self, text):
76
        """Convert text string to a list of token indices.
77

78
        Args:
79
            text (str): Text.
H
huangyuxin 已提交
80

81 82
        Returns:
            List[int]: List of token indices.
83
        """
84
        tokens = self.tokenize(text)
H
Hui Zhang 已提交
85 86
        ids = []
        for token in tokens:
H
huangyuxin 已提交
87 88
            if '' in self.vocab_dict and token == ' ':
                token = ''
89 90
            token = token if token in self.vocab_dict else self.unk
            ids.append(self.vocab_dict[token])
H
Hui Zhang 已提交
91
        return ids
92

93 94
    def defeaturize(self, idxs):
        """Convert a list of token indices to text string,
H
huangyuxin 已提交
95
        ignore index after eos_id.
96 97 98 99 100

        Args:
            idxs (List[int]): List of token indices.

        Returns:
101
            str: Text.
102 103 104 105 106 107 108 109 110
        """
        tokens = []
        for idx in idxs:
            if idx == self.eos_id:
                break
            tokens.append(self._id2token[idx])
        text = self.detokenize(tokens)
        return text

H
Hui Zhang 已提交
111
    def char_tokenize(self, text, replace_space=True):
112 113 114 115
        """Character tokenizer.

        Args:
            text (str): text string.
H
Hui Zhang 已提交
116
            replace_space (bool): False only used by build_vocab.py.
117 118 119 120

        Returns:
            List[str]: tokens.
        """
H
Hui Zhang 已提交
121
        text = text.strip()
H
Hui Zhang 已提交
122 123
        if replace_space:
            text = text.replace(" ", SPACE)
H
Hui Zhang 已提交
124
        return list(text)
125

126 127 128 129 130 131 132 133 134
    def char_detokenize(self, tokens):
        """Character detokenizer.

        Args:
            tokens (List[str]): tokens.

        Returns:
           str: text string.
        """
H
Hui Zhang 已提交
135
        tokens = tokens.replace(SPACE, " ")
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        return "".join(tokens)

    def word_tokenize(self, text):
        """Word tokenizer, separate by <space>."""
        return text.strip().split()

    def word_detokenize(self, tokens):
        """Word detokenizer, separate by <space>."""
        return " ".join(tokens)

    def spm_tokenize(self, text):
        """spm tokenize.

        Args:
            text (str): text string.

        Returns:
            List[str]: sentence pieces str code
        """
        stats = {"num_empty": 0, "num_filtered": 0}

        def valid(line):
            return True

        def encode(l):
            return self.sp.EncodeAsPieces(l)

        def encode_line(line):
            line = line.strip()
            if len(line) > 0:
                line = encode(line)
                if valid(line):
                    return line
                else:
                    stats["num_filtered"] += 1
            else:
                stats["num_empty"] += 1
            return None

        enc_line = encode_line(text)
        return enc_line

    def spm_detokenize(self, tokens, input_format='piece'):
        """spm detokenize.

        Args:
            ids (List[str]): tokens.

        Returns:
            str: text
        """
        if input_format == "piece":

            def decode(l):
                return "".join(self.sp.DecodePieces(l))
        elif input_format == "id":

            def decode(l):
                return "".join(self.sp.DecodeIds(l))

        return decode(tokens)

198
    def _load_vocabulary_from_file(self, vocab_filepath: str, maskctc: bool):
199
        """Load vocabulary from file."""
200 201
        vocab_list = load_dict(vocab_filepath, maskctc)
        assert vocab_list is not None
H
Hui Zhang 已提交
202
        assert SPACE in vocab_list
203

204 205 206 207
        id2token = dict(
            [(idx, token) for (idx, token) in enumerate(vocab_list)])
        token2id = dict(
            [(token, idx) for (idx, token) in enumerate(vocab_list)])
H
Hui Zhang 已提交
208 209 210 211

        unk_id = vocab_list.index(UNK) if UNK in vocab_list else -1
        eos_id = vocab_list.index(EOS) if EOS in vocab_list else -1

212
        return token2id, id2token, vocab_list, unk_id, eos_id