label_ops.py 21.2 KB
Newer Older
W
WenmuZhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import numpy as np
T
tink2123 已提交
21
import string
L
LDOUBLEV 已提交
22
import json
W
WenmuZhou 已提交
23

T
tink2123 已提交
24 25
from ppocr.utils.logging import get_logger

W
WenmuZhou 已提交
26 27 28 29 30 31 32 33 34 35 36 37

class ClsLabelEncode(object):
    def __init__(self, label_list, **kwargs):
        self.label_list = label_list

    def __call__(self, data):
        label = data['label']
        if label not in self.label_list:
            return None
        label = self.label_list.index(label)
        data['label'] = label
        return data
W
WenmuZhou 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57


class DetLabelEncode(object):
    def __init__(self, **kwargs):
        pass

    def __call__(self, data):
        label = data['label']
        label = json.loads(label)
        nBox = len(label)
        boxes, txts, txt_tags = [], [], []
        for bno in range(0, nBox):
            box = label[bno]['points']
            txt = label[bno]['transcription']
            boxes.append(box)
            txts.append(txt)
            if txt in ['*', '###']:
                txt_tags.append(True)
            else:
                txt_tags.append(False)
L
LDOUBLEV 已提交
58 59
        if len(boxes) == 0:
            return None
M
MissPenguin 已提交
60
        boxes = self.expand_points_num(boxes)
L
LDOUBLEV 已提交
61 62
        boxes = np.array(boxes, dtype=np.float32)
        txt_tags = np.array(txt_tags, dtype=np.bool)
W
WenmuZhou 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

        data['polys'] = boxes
        data['texts'] = txts
        data['ignore_tags'] = txt_tags
        return data

    def order_points_clockwise(self, pts):
        rect = np.zeros((4, 2), dtype="float32")
        s = pts.sum(axis=1)
        rect[0] = pts[np.argmin(s)]
        rect[2] = pts[np.argmax(s)]
        diff = np.diff(pts, axis=1)
        rect[1] = pts[np.argmin(diff)]
        rect[3] = pts[np.argmax(diff)]
        return rect

M
MissPenguin 已提交
79 80 81 82 83 84 85 86 87 88 89
    def expand_points_num(self, boxes):
        max_points_num = 0
        for box in boxes:
            if len(box) > max_points_num:
                max_points_num = len(box)
        ex_boxes = []
        for box in boxes:
            ex_box = box + [box[-1]] * (max_points_num - len(box))
            ex_boxes.append(ex_box)
        return ex_boxes

W
WenmuZhou 已提交
90 91 92 93 94 95 96 97 98 99

class BaseRecLabelEncode(object):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False):

        self.max_text_len = max_text_length
T
tink2123 已提交
100 101
        self.beg_str = "sos"
        self.end_str = "eos"
T
tink2123 已提交
102
        self.lower = False
T
tink2123 已提交
103 104 105 106 107 108

        if character_dict_path is None:
            logger = get_logger()
            logger.warning(
                "The character_dict_path is None, model can only recognize number and lower letters"
            )
W
WenmuZhou 已提交
109 110
            self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
            dict_character = list(self.character_str)
T
tink2123 已提交
111 112
            self.lower = True
        else:
W
WenmuZhou 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
            self.character_str = ""
            with open(character_dict_path, "rb") as fin:
                lines = fin.readlines()
                for line in lines:
                    line = line.decode('utf-8').strip("\n").strip("\r\n")
                    self.character_str += line
            if use_space_char:
                self.character_str += " "
            dict_character = list(self.character_str)
        dict_character = self.add_special_char(dict_character)
        self.dict = {}
        for i, char in enumerate(dict_character):
            self.dict[char] = i
        self.character = dict_character

    def add_special_char(self, dict_character):
        return dict_character

    def encode(self, text):
        """convert text-label into text-index.
        input:
            text: text labels of each image. [batch_size]

        output:
            text: concatenated text index for CTCLoss.
                    [sum(text_lengths)] = [text_index_0 + text_index_1 + ... + text_index_(n - 1)]
            length: length of each text. [batch_size]
        """
W
WenmuZhou 已提交
141
        if len(text) == 0 or len(text) > self.max_text_len:
W
WenmuZhou 已提交
142
            return None
T
tink2123 已提交
143
        if self.lower:
W
WenmuZhou 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156
            text = text.lower()
        text_list = []
        for char in text:
            if char not in self.dict:
                # logger = get_logger()
                # logger.warning('{} is not in dict'.format(char))
                continue
            text_list.append(self.dict[char])
        if len(text_list) == 0:
            return None
        return text_list


T
Topdu 已提交
157 158 159 160 161 162 163 164 165
class NRTRLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):

T
tink2123 已提交
166 167
        super(NRTRLabelEncode, self).__init__(
            max_text_length, character_dict_path, use_space_char)
T
tink2123 已提交
168

T
Topdu 已提交
169 170 171 172 173
    def __call__(self, data):
        text = data['label']
        text = self.encode(text)
        if text is None:
            return None
T
Topdu 已提交
174 175
        if len(text) >= self.max_text_len - 1:
            return None
T
Topdu 已提交
176 177 178 179 180 181
        data['length'] = np.array(len(text))
        text.insert(0, 2)
        text.append(3)
        text = text + [0] * (self.max_text_len - len(text))
        data['label'] = np.array(text)
        return data
T
tink2123 已提交
182

T
Topdu 已提交
183
    def add_special_char(self, dict_character):
T
tink2123 已提交
184
        dict_character = ['blank', '<unk>', '<s>', '</s>'] + dict_character
T
Topdu 已提交
185 186
        return dict_character

T
tink2123 已提交
187

W
WenmuZhou 已提交
188 189 190 191 192 193 194 195
class CTCLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):
T
tink2123 已提交
196 197
        super(CTCLabelEncode, self).__init__(
            max_text_length, character_dict_path, use_space_char)
W
WenmuZhou 已提交
198 199 200 201 202 203 204 205 206

    def __call__(self, data):
        text = data['label']
        text = self.encode(text)
        if text is None:
            return None
        data['length'] = np.array(len(text))
        text = text + [0] * (self.max_text_len - len(text))
        data['label'] = np.array(text)
207 208 209 210 211

        label = [0] * len(self.character)
        for x in text:
            label[x] += 1
        data['label_ace'] = np.array(label)
W
WenmuZhou 已提交
212 213 214 215 216 217 218
        return data

    def add_special_char(self, dict_character):
        dict_character = ['blank'] + dict_character
        return dict_character


J
Jethong 已提交
219
class E2ELabelEncodeTest(BaseRecLabelEncode):
J
Jethong 已提交
220 221 222 223 224
    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):
T
tink2123 已提交
225 226
        super(E2ELabelEncodeTest, self).__init__(
            max_text_length, character_dict_path, use_space_char)
J
Jethong 已提交
227 228

    def __call__(self, data):
J
Jethong 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        import json
        padnum = len(self.dict)
        label = data['label']
        label = json.loads(label)
        nBox = len(label)
        boxes, txts, txt_tags = [], [], []
        for bno in range(0, nBox):
            box = label[bno]['points']
            txt = label[bno]['transcription']
            boxes.append(box)
            txts.append(txt)
            if txt in ['*', '###']:
                txt_tags.append(True)
            else:
                txt_tags.append(False)
        boxes = np.array(boxes, dtype=np.float32)
        txt_tags = np.array(txt_tags, dtype=np.bool)
        data['polys'] = boxes
J
Jethong 已提交
247
        data['ignore_tags'] = txt_tags
J
Jethong 已提交
248
        temp_texts = []
J
Jethong 已提交
249
        for text in txts:
J
Jethong 已提交
250 251 252 253
            text = text.lower()
            text = self.encode(text)
            if text is None:
                return None
J
Jethong 已提交
254 255
            text = text + [padnum] * (self.max_text_len - len(text)
                                      )  # use 36 to pad
J
Jethong 已提交
256 257 258 259 260
            temp_texts.append(text)
        data['texts'] = np.array(temp_texts)
        return data


J
Jethong 已提交
261
class E2ELabelEncodeTrain(object):
J
Jethong 已提交
262 263
    def __init__(self, **kwargs):
        pass
J
Jethong 已提交
264 265

    def __call__(self, data):
J
Jethong 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        import json
        label = data['label']
        label = json.loads(label)
        nBox = len(label)
        boxes, txts, txt_tags = [], [], []
        for bno in range(0, nBox):
            box = label[bno]['points']
            txt = label[bno]['transcription']
            boxes.append(box)
            txts.append(txt)
            if txt in ['*', '###']:
                txt_tags.append(True)
            else:
                txt_tags.append(False)
        boxes = np.array(boxes, dtype=np.float32)
        txt_tags = np.array(txt_tags, dtype=np.bool)

        data['polys'] = boxes
        data['texts'] = txts
J
Jethong 已提交
285
        data['ignore_tags'] = txt_tags
J
Jethong 已提交
286 287 288
        return data


W
WenmuZhou 已提交
289 290 291 292 293 294 295 296
class AttnLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):
T
tink2123 已提交
297 298
        super(AttnLabelEncode, self).__init__(
            max_text_length, character_dict_path, use_space_char)
W
WenmuZhou 已提交
299 300

    def add_special_char(self, dict_character):
L
LDOUBLEV 已提交
301 302 303
        self.beg_str = "sos"
        self.end_str = "eos"
        dict_character = [self.beg_str] + dict_character + [self.end_str]
W
WenmuZhou 已提交
304 305
        return dict_character

L
LDOUBLEV 已提交
306 307
    def __call__(self, data):
        text = data['label']
W
WenmuZhou 已提交
308
        text = self.encode(text)
L
LDOUBLEV 已提交
309 310
        if text is None:
            return None
L
LDOUBLEV 已提交
311
        if len(text) >= self.max_text_len:
L
LDOUBLEV 已提交
312 313 314
            return None
        data['length'] = np.array(len(text))
        text = [0] + text + [len(self.character) - 1] + [0] * (self.max_text_len
T
tink2123 已提交
315
                                                               - len(text) - 2)
L
LDOUBLEV 已提交
316 317 318 319 320 321 322
        data['label'] = np.array(text)
        return data

    def get_ignored_tokens(self):
        beg_idx = self.get_beg_end_flag_idx("beg")
        end_idx = self.get_beg_end_flag_idx("end")
        return [beg_idx, end_idx]
W
WenmuZhou 已提交
323 324 325 326 327 328 329 330 331 332

    def get_beg_end_flag_idx(self, beg_or_end):
        if beg_or_end == "beg":
            idx = np.array(self.dict[self.beg_str])
        elif beg_or_end == "end":
            idx = np.array(self.dict[self.end_str])
        else:
            assert False, "Unsupport type %s in get_beg_end_flag_idx" \
                          % beg_or_end
        return idx
T
tink2123 已提交
333 334


T
tink2123 已提交
335 336 337 338 339 340 341 342
class SEEDLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):
T
tink2123 已提交
343 344
        super(SEEDLabelEncode, self).__init__(
            max_text_length, character_dict_path, use_space_char)
T
tink2123 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357

    def add_special_char(self, dict_character):
        self.end_str = "eos"
        dict_character = dict_character + [self.end_str]
        return dict_character

    def __call__(self, data):
        text = data['label']
        text = self.encode(text)
        if text is None:
            return None
        if len(text) >= self.max_text_len:
            return None
T
rm anno  
tink2123 已提交
358
        data['length'] = np.array(len(text)) + 1  # conclude eos
T
tink2123 已提交
359 360 361 362 363 364
        text = text + [len(self.character) - 1] * (self.max_text_len - len(text)
                                                   )
        data['label'] = np.array(text)
        return data


T
tink2123 已提交
365 366 367 368 369 370 371 372
class SRNLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length=25,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):
T
tink2123 已提交
373 374
        super(SRNLabelEncode, self).__init__(
            max_text_length, character_dict_path, use_space_char)
T
tink2123 已提交
375 376 377 378 379 380 381 382

    def add_special_char(self, dict_character):
        dict_character = dict_character + [self.beg_str, self.end_str]
        return dict_character

    def __call__(self, data):
        text = data['label']
        text = self.encode(text)
T
tink2123 已提交
383
        char_num = len(self.character)
T
tink2123 已提交
384 385 386 387 388
        if text is None:
            return None
        if len(text) > self.max_text_len:
            return None
        data['length'] = np.array(len(text))
T
tink2123 已提交
389
        text = text + [char_num - 1] * (self.max_text_len - len(text))
T
tink2123 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
        data['label'] = np.array(text)
        return data

    def get_ignored_tokens(self):
        beg_idx = self.get_beg_end_flag_idx("beg")
        end_idx = self.get_beg_end_flag_idx("end")
        return [beg_idx, end_idx]

    def get_beg_end_flag_idx(self, beg_or_end):
        if beg_or_end == "beg":
            idx = np.array(self.dict[self.beg_str])
        elif beg_or_end == "end":
            idx = np.array(self.dict[self.end_str])
        else:
            assert False, "Unsupport type %s in get_beg_end_flag_idx" \
                          % beg_or_end
        return idx
M
MissPenguin 已提交
407

L
LDOUBLEV 已提交
408

M
MissPenguin 已提交
409 410
class TableLabelEncode(object):
    """ Convert between text-label and text-index """
L
LDOUBLEV 已提交
411 412 413 414 415 416 417 418

    def __init__(self,
                 max_text_length,
                 max_elem_length,
                 max_cell_num,
                 character_dict_path,
                 span_weight=1.0,
                 **kwargs):
M
MissPenguin 已提交
419 420 421
        self.max_text_length = max_text_length
        self.max_elem_length = max_elem_length
        self.max_cell_num = max_cell_num
L
LDOUBLEV 已提交
422 423
        list_character, list_elem = self.load_char_elem_dict(
            character_dict_path)
M
MissPenguin 已提交
424 425 426 427 428 429 430 431 432
        list_character = self.add_special_char(list_character)
        list_elem = self.add_special_char(list_elem)
        self.dict_character = {}
        for i, char in enumerate(list_character):
            self.dict_character[char] = i
        self.dict_elem = {}
        for i, elem in enumerate(list_elem):
            self.dict_elem[elem] = i
        self.span_weight = span_weight
L
LDOUBLEV 已提交
433

M
MissPenguin 已提交
434 435 436 437 438
    def load_char_elem_dict(self, character_dict_path):
        list_character = []
        list_elem = []
        with open(character_dict_path, "rb") as fin:
            lines = fin.readlines()
W
WenmuZhou 已提交
439
            substr = lines[0].decode('utf-8').strip("\r\n").split("\t")
M
MissPenguin 已提交
440 441
            character_num = int(substr[0])
            elem_num = int(substr[1])
L
LDOUBLEV 已提交
442
            for cno in range(1, 1 + character_num):
W
WenmuZhou 已提交
443
                character = lines[cno].decode('utf-8').strip("\r\n")
M
MissPenguin 已提交
444
                list_character.append(character)
L
LDOUBLEV 已提交
445
            for eno in range(1 + character_num, 1 + character_num + elem_num):
W
WenmuZhou 已提交
446
                elem = lines[eno].decode('utf-8').strip("\r\n")
M
MissPenguin 已提交
447 448
                list_elem.append(elem)
        return list_character, list_elem
L
LDOUBLEV 已提交
449

M
MissPenguin 已提交
450 451 452 453 454
    def add_special_char(self, list_character):
        self.beg_str = "sos"
        self.end_str = "eos"
        list_character = [self.beg_str] + list_character + [self.end_str]
        return list_character
L
LDOUBLEV 已提交
455

M
MissPenguin 已提交
456 457 458 459 460 461
    def get_span_idx_list(self):
        span_idx_list = []
        for elem in self.dict_elem:
            if 'span' in elem:
                span_idx_list.append(self.dict_elem[elem])
        return span_idx_list
L
LDOUBLEV 已提交
462

M
MissPenguin 已提交
463 464 465 466 467 468 469 470
    def __call__(self, data):
        cells = data['cells']
        structure = data['structure']['tokens']
        structure = self.encode(structure, 'elem')
        if structure is None:
            return None
        elem_num = len(structure)
        structure = [0] + structure + [len(self.dict_elem) - 1]
L
LDOUBLEV 已提交
471 472
        structure = structure + [0] * (self.max_elem_length + 2 - len(structure)
                                       )
M
MissPenguin 已提交
473 474 475 476 477
        structure = np.array(structure)
        data['structure'] = structure
        elem_char_idx1 = self.dict_elem['<td>']
        elem_char_idx2 = self.dict_elem['<td']
        span_idx_list = self.get_span_idx_list()
L
LDOUBLEV 已提交
478 479
        td_idx_list = np.logical_or(structure == elem_char_idx1,
                                    structure == elem_char_idx2)
M
MissPenguin 已提交
480
        td_idx_list = np.where(td_idx_list)[0]
L
LDOUBLEV 已提交
481 482 483

        structure_mask = np.ones(
            (self.max_elem_length + 2, 1), dtype=np.float32)
M
MissPenguin 已提交
484
        bbox_list = np.zeros((self.max_elem_length + 2, 4), dtype=np.float32)
L
LDOUBLEV 已提交
485 486
        bbox_list_mask = np.zeros(
            (self.max_elem_length + 2, 1), dtype=np.float32)
M
MissPenguin 已提交
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        img_height, img_width, img_ch = data['image'].shape
        if len(span_idx_list) > 0:
            span_weight = len(td_idx_list) * 1.0 / len(span_idx_list)
            span_weight = min(max(span_weight, 1.0), self.span_weight)
        for cno in range(len(cells)):
            if 'bbox' in cells[cno]:
                bbox = cells[cno]['bbox'].copy()
                bbox[0] = bbox[0] * 1.0 / img_width
                bbox[1] = bbox[1] * 1.0 / img_height
                bbox[2] = bbox[2] * 1.0 / img_width
                bbox[3] = bbox[3] * 1.0 / img_height
                td_idx = td_idx_list[cno]
                bbox_list[td_idx] = bbox
                bbox_list_mask[td_idx] = 1.0
                cand_span_idx = td_idx + 1
                if cand_span_idx < (self.max_elem_length + 2):
                    if structure[cand_span_idx] in span_idx_list:
                        structure_mask[cand_span_idx] = span_weight

        data['bbox_list'] = bbox_list
        data['bbox_list_mask'] = bbox_list_mask
        data['structure_mask'] = structure_mask
        char_beg_idx = self.get_beg_end_flag_idx('beg', 'char')
        char_end_idx = self.get_beg_end_flag_idx('end', 'char')
        elem_beg_idx = self.get_beg_end_flag_idx('beg', 'elem')
        elem_end_idx = self.get_beg_end_flag_idx('end', 'elem')
L
LDOUBLEV 已提交
513 514 515 516 517
        data['sp_tokens'] = np.array([
            char_beg_idx, char_end_idx, elem_beg_idx, elem_end_idx,
            elem_char_idx1, elem_char_idx2, self.max_text_length,
            self.max_elem_length, self.max_cell_num, elem_num
        ])
M
MissPenguin 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
        return data

    def encode(self, text, char_or_elem):
        """convert text-label into text-index.
        """
        if char_or_elem == "char":
            max_len = self.max_text_length
            current_dict = self.dict_character
        else:
            max_len = self.max_elem_length
            current_dict = self.dict_elem
        if len(text) > max_len:
            return None
        if len(text) == 0:
            if char_or_elem == "char":
                return [self.dict_character['space']]
            else:
                return None
        text_list = []
        for char in text:
            if char not in current_dict:
                return None
            text_list.append(current_dict[char])
        if len(text_list) == 0:
            if char_or_elem == "char":
                return [self.dict_character['space']]
            else:
                return None
        return text_list

    def get_ignored_tokens(self, char_or_elem):
        beg_idx = self.get_beg_end_flag_idx("beg", char_or_elem)
        end_idx = self.get_beg_end_flag_idx("end", char_or_elem)
        return [beg_idx, end_idx]

    def get_beg_end_flag_idx(self, beg_or_end, char_or_elem):
        if char_or_elem == "char":
            if beg_or_end == "beg":
                idx = np.array(self.dict_character[self.beg_str])
            elif beg_or_end == "end":
                idx = np.array(self.dict_character[self.end_str])
            else:
                assert False, "Unsupport type %s in get_beg_end_flag_idx of char" \
                              % beg_or_end
        elif char_or_elem == "elem":
            if beg_or_end == "beg":
                idx = np.array(self.dict_elem[self.beg_str])
            elif beg_or_end == "end":
                idx = np.array(self.dict_elem[self.end_str])
            else:
                assert False, "Unsupport type %s in get_beg_end_flag_idx of elem" \
L
LDOUBLEV 已提交
569
                              % beg_or_end
M
MissPenguin 已提交
570 571
        else:
            assert False, "Unsupport type %s in char_or_elem" \
L
LDOUBLEV 已提交
572
                              % char_or_elem
M
MissPenguin 已提交
573
        return idx
A
andyjpaddle 已提交
574 575 576 577 578 579 580 581 582 583


class SARLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 use_space_char=False,
                 **kwargs):
T
tink2123 已提交
584 585
        super(SARLabelEncode, self).__init__(
            max_text_length, character_dict_path, use_space_char)
A
andyjpaddle 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

    def add_special_char(self, dict_character):
        beg_end_str = "<BOS/EOS>"
        unknown_str = "<UKN>"
        padding_str = "<PAD>"
        dict_character = dict_character + [unknown_str]
        self.unknown_idx = len(dict_character) - 1
        dict_character = dict_character + [beg_end_str]
        self.start_idx = len(dict_character) - 1
        self.end_idx = len(dict_character) - 1
        dict_character = dict_character + [padding_str]
        self.padding_idx = len(dict_character) - 1

        return dict_character

    def __call__(self, data):
        text = data['label']
        text = self.encode(text)
        if text is None:
            return None
        if len(text) >= self.max_text_len - 1:
            return None
        data['length'] = np.array(len(text))
        target = [self.start_idx] + text + [self.end_idx]
        padded_text = [self.padding_idx for _ in range(self.max_text_len)]
T
tink2123 已提交
611

A
andyjpaddle 已提交
612 613 614 615 616 617
        padded_text[:len(target)] = target
        data['label'] = np.array(padded_text)
        return data

    def get_ignored_tokens(self):
        return [self.padding_idx]