"docs/source/vscode:/vscode.git/clone" did not exist on "f98b745a81df1613a9c5f1d5986456663f86c457"
label_ops.py 12.9 KB
Newer Older
WenmuZhou's avatar
WenmuZhou committed
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
tink2123's avatar
tink2123 committed
21
import string
WenmuZhou's avatar
WenmuZhou committed
22
23
24
25
26
27
28
29
30
31
32
33
34


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
WenmuZhou's avatar
WenmuZhou committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55


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

    def __call__(self, data):
        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)
MissPenguin's avatar
MissPenguin committed
56
        boxes = self.expand_points_num(boxes)
WenmuZhou's avatar
WenmuZhou committed
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
        boxes = np.array(boxes, dtype=np.float32)
        txt_tags = np.array(txt_tags, dtype=np.bool)

        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

MissPenguin's avatar
MissPenguin committed
75
76
77
78
79
80
81
82
83
84
85
    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

WenmuZhou's avatar
WenmuZhou committed
86
87
88
89
90
91
92
93
94

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

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 character_type='ch',
                 use_space_char=False):
MissPenguin's avatar
MissPenguin committed
95
        support_character_type = [
tink2123's avatar
tink2123 committed
96
97
            'ch', 'en', 'EN_symbol', 'french', 'german', 'japan', 'korean',
            'EN', 'it', 'xi', 'pu', 'ru', 'ar', 'ta', 'ug', 'fa', 'ur', 'rs',
tink2123's avatar
tink2123 committed
98
            'oc', 'rsc', 'bg', 'uk', 'be', 'te', 'ka', 'chinese_cht', 'hi',
Topdu's avatar
Topdu committed
99
            'mr', 'ne', 'latin', 'arabic', 'cyrillic', 'devanagari','dict_99'
MissPenguin's avatar
MissPenguin committed
100
        ]
WenmuZhou's avatar
WenmuZhou committed
101
        assert character_type in support_character_type, "Only {} are supported now but get {}".format(
MissPenguin's avatar
MissPenguin committed
102
            support_character_type, character_type)
WenmuZhou's avatar
WenmuZhou committed
103
104

        self.max_text_len = max_text_length
tink2123's avatar
tink2123 committed
105
106
        self.beg_str = "sos"
        self.end_str = "eos"
WenmuZhou's avatar
WenmuZhou committed
107
108
109
        if character_type == "en":
            self.character_str = "0123456789abcdefghijklmnopqrstuvwxyz"
            dict_character = list(self.character_str)
tink2123's avatar
tink2123 committed
110
        elif character_type == "EN_symbol":
tink2123's avatar
tink2123 committed
111
112
113
114
            # same with ASTER setting (use 94 char).
            self.character_str = string.printable[:-6]
            dict_character = list(self.character_str)
        elif character_type in support_character_type:
WenmuZhou's avatar
WenmuZhou committed
115
            self.character_str = ""
tink2123's avatar
tink2123 committed
116
117
            assert character_dict_path is not None, "character_dict_path should not be None when character_type is {}".format(
                character_type)
WenmuZhou's avatar
WenmuZhou committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            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)
        self.character_type = character_type
        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]
        """
WenmuZhou's avatar
WenmuZhou committed
146
        if len(text) == 0 or len(text) > self.max_text_len:
WenmuZhou's avatar
WenmuZhou committed
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
            return None
        if self.character_type == "en":
            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


Topdu's avatar
Topdu committed
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
class NRTRLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

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

        super(NRTRLabelEncode,
              self).__init__(max_text_length, character_dict_path,
                             character_type, use_space_char)
    def __call__(self, data):
        text = data['label']
        text = self.encode(text)
        if text is None:
            return None
        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
    def add_special_char(self, dict_character):
        dict_character = ['blank','<unk>','<s>','</s>'] + dict_character
        return dict_character

WenmuZhou's avatar
WenmuZhou committed
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
class CTCLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 character_type='ch',
                 use_space_char=False,
                 **kwargs):
        super(CTCLabelEncode,
              self).__init__(max_text_length, character_dict_path,
                             character_type, use_space_char)

    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)
        return data

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


Jethong's avatar
Jethong committed
218
class E2ELabelEncodeTest(BaseRecLabelEncode):
Jethong's avatar
Jethong committed
219
220
221
222
223
224
    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 character_type='EN',
                 use_space_char=False,
                 **kwargs):
Jethong's avatar
Jethong committed
225
        super(E2ELabelEncodeTest,
Jethong's avatar
Jethong committed
226
227
228
229
              self).__init__(max_text_length, character_dict_path,
                             character_type, use_space_char)

    def __call__(self, data):
Jethong's avatar
Jethong committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
        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
Jethong's avatar
Jethong committed
248
        data['ignore_tags'] = txt_tags
Jethong's avatar
Jethong committed
249
        temp_texts = []
Jethong's avatar
Jethong committed
250
        for text in txts:
Jethong's avatar
Jethong committed
251
252
253
254
            text = text.lower()
            text = self.encode(text)
            if text is None:
                return None
Jethong's avatar
Jethong committed
255
256
            text = text + [padnum] * (self.max_text_len - len(text)
                                      )  # use 36 to pad
Jethong's avatar
Jethong committed
257
258
259
260
261
            temp_texts.append(text)
        data['texts'] = np.array(temp_texts)
        return data


Jethong's avatar
Jethong committed
262
class E2ELabelEncodeTrain(object):
Jethong's avatar
Jethong committed
263
264
    def __init__(self, **kwargs):
        pass
Jethong's avatar
Jethong committed
265
266

    def __call__(self, data):
Jethong's avatar
Jethong committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
        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
Jethong's avatar
Jethong committed
286
        data['ignore_tags'] = txt_tags
Jethong's avatar
Jethong committed
287
288
289
        return data


WenmuZhou's avatar
WenmuZhou committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
class AttnLabelEncode(BaseRecLabelEncode):
    """ Convert between text-label and text-index """

    def __init__(self,
                 max_text_length,
                 character_dict_path=None,
                 character_type='ch',
                 use_space_char=False,
                 **kwargs):
        super(AttnLabelEncode,
              self).__init__(max_text_length, character_dict_path,
                             character_type, use_space_char)

    def add_special_char(self, dict_character):
LDOUBLEV's avatar
LDOUBLEV committed
304
305
306
        self.beg_str = "sos"
        self.end_str = "eos"
        dict_character = [self.beg_str] + dict_character + [self.end_str]
WenmuZhou's avatar
WenmuZhou committed
307
308
        return dict_character

LDOUBLEV's avatar
LDOUBLEV committed
309
310
    def __call__(self, data):
        text = data['label']
WenmuZhou's avatar
WenmuZhou committed
311
        text = self.encode(text)
LDOUBLEV's avatar
LDOUBLEV committed
312
313
        if text is None:
            return None
LDOUBLEV's avatar
LDOUBLEV committed
314
        if len(text) >= self.max_text_len:
LDOUBLEV's avatar
LDOUBLEV committed
315
316
317
            return None
        data['length'] = np.array(len(text))
        text = [0] + text + [len(self.character) - 1] + [0] * (self.max_text_len
tink2123's avatar
tink2123 committed
318
                                                               - len(text) - 2)
LDOUBLEV's avatar
LDOUBLEV committed
319
320
321
322
323
324
325
        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]
WenmuZhou's avatar
WenmuZhou committed
326
327
328
329
330
331
332
333
334
335

    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
tink2123's avatar
tink2123 committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357


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

    def __init__(self,
                 max_text_length=25,
                 character_dict_path=None,
                 character_type='en',
                 use_space_char=False,
                 **kwargs):
        super(SRNLabelEncode,
              self).__init__(max_text_length, character_dict_path,
                             character_type, use_space_char)

    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)
tink2123's avatar
tink2123 committed
358
        char_num = len(self.character)
tink2123's avatar
tink2123 committed
359
360
361
362
363
        if text is None:
            return None
        if len(text) > self.max_text_len:
            return None
        data['length'] = np.array(len(text))
tink2123's avatar
tink2123 committed
364
        text = text + [char_num - 1] * (self.max_text_len - len(text))
tink2123's avatar
tink2123 committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
        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