rec_model.py 9.2 KB
Newer Older
L
LDOUBLEV 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
# Copyright (c) 2020 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.

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

from paddle import fluid

from ppocr.utils.utility import create_module
from ppocr.utils.utility import initial_logger
logger = initial_logger()
from copy import deepcopy


class RecModel(object):
    def __init__(self, params):
        super(RecModel, self).__init__()
        global_params = params['Global']
        char_num = global_params['char_ops'].get_char_num()
        global_params['char_num'] = char_num
T
tink2123 已提交
33
        self.char_type = global_params['character_type']
T
tink2123 已提交
34
        self.infer_img = global_params['infer_img']
L
LDOUBLEV 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
        if "TPS" in params:
            tps_params = deepcopy(params["TPS"])
            tps_params.update(global_params)
            self.tps = create_module(tps_params['function'])\
                (params=tps_params)
        else:
            self.tps = None

        backbone_params = deepcopy(params["Backbone"])
        backbone_params.update(global_params)
        self.backbone = create_module(backbone_params['function'])\
                (params=backbone_params)

        head_params = deepcopy(params["Head"])
        head_params.update(global_params)
        self.head = create_module(head_params['function'])\
                (params=head_params)

        loss_params = deepcopy(params["Loss"])
        loss_params.update(global_params)
        self.loss = create_module(loss_params['function'])\
                (params=loss_params)

        self.loss_type = global_params['loss_type']
        self.image_shape = global_params['image_shape']
        self.max_text_length = global_params['max_text_length']
T
fix bug  
tink2123 已提交
61
        if "num_heads" in global_params:
T
tink2123 已提交
62 63 64
            self.num_heads = global_params["num_heads"]
        else:
            self.num_heads = None
L
LDOUBLEV 已提交
65 66 67 68 69

    def create_feed(self, mode):
        image_shape = deepcopy(self.image_shape)
        image_shape.insert(0, -1)
        if mode == "train":
T
tink2123 已提交
70
            image = fluid.data(name='image', shape=image_shape, dtype='float32')
B
baiyfbupt 已提交
71
            image.stop_gradient = False
L
LDOUBLEV 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84
            if self.loss_type == "attention":
                label_in = fluid.data(
                    name='label_in',
                    shape=[None, 1],
                    dtype='int32',
                    lod_level=1)
                label_out = fluid.data(
                    name='label_out',
                    shape=[None, 1],
                    dtype='int32',
                    lod_level=1)
                feed_list = [image, label_in, label_out]
                labels = {'label_in': label_in, 'label_out': label_out}
T
tink2123 已提交
85
            elif self.loss_type == "srn":
T
tink2123 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
                encoder_word_pos = fluid.data(
                    name="encoder_word_pos",
                    shape=[
                        -1, int((image_shape[-2] / 8) * (image_shape[-1] / 8)),
                        1
                    ],
                    dtype="int64")
                gsrm_word_pos = fluid.data(
                    name="gsrm_word_pos",
                    shape=[-1, self.max_text_length, 1],
                    dtype="int64")
                gsrm_slf_attn_bias1 = fluid.data(
                    name="gsrm_slf_attn_bias1",
                    shape=[
                        -1, self.num_heads, self.max_text_length,
                        self.max_text_length
T
tink2123 已提交
102 103
                    ],
                    dtype="float32")
T
tink2123 已提交
104 105 106 107 108
                gsrm_slf_attn_bias2 = fluid.data(
                    name="gsrm_slf_attn_bias2",
                    shape=[
                        -1, self.num_heads, self.max_text_length,
                        self.max_text_length
T
tink2123 已提交
109 110
                    ],
                    dtype="float32")
T
tink2123 已提交
111 112
                lbl_weight = fluid.layers.data(
                    name="lbl_weight", shape=[-1, 1], dtype='int64')
T
tink2123 已提交
113 114
                label = fluid.data(
                    name='label', shape=[-1, 1], dtype='int32', lod_level=1)
T
tink2123 已提交
115 116 117 118 119 120 121 122 123 124 125 126
                feed_list = [
                    image, label, encoder_word_pos, gsrm_word_pos,
                    gsrm_slf_attn_bias1, gsrm_slf_attn_bias2, lbl_weight
                ]
                labels = {
                    'label': label,
                    'encoder_word_pos': encoder_word_pos,
                    'gsrm_word_pos': gsrm_word_pos,
                    'gsrm_slf_attn_bias1': gsrm_slf_attn_bias1,
                    'gsrm_slf_attn_bias2': gsrm_slf_attn_bias2,
                    'lbl_weight': lbl_weight
                }
L
LDOUBLEV 已提交
127 128 129 130 131 132 133 134 135 136 137
            else:
                label = fluid.data(
                    name='label', shape=[None, 1], dtype='int32', lod_level=1)
                feed_list = [image, label]
                labels = {'label': label}
            loader = fluid.io.DataLoader.from_generator(
                feed_list=feed_list,
                capacity=64,
                use_double_buffer=True,
                iterable=False)
        else:
T
tink2123 已提交
138 139
            labels = None
            loader = None
T
tink2123 已提交
140
            if self.char_type == "ch" and self.infer_img and self.loss_type != "srn":
T
tink2123 已提交
141 142 143 144 145
                image_shape[-1] = -1
                if self.tps != None:
                    logger.info(
                        "WARNRNG!!!\n"
                        "TPS does not support variable shape in chinese!"
T
tink2123 已提交
146
                        "We set img_shape to be the same , it may affect the inference effect"
T
tink2123 已提交
147
                    )
T
tink2123 已提交
148
                    image_shape = deepcopy(self.image_shape)
T
tink2123 已提交
149
            image = fluid.data(name='image', shape=image_shape, dtype='float32')
B
baiyfbupt 已提交
150
            image.stop_gradient = False
T
tink2123 已提交
151
            if self.loss_type == "srn":
T
tink2123 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
                encoder_word_pos = fluid.data(
                    name="encoder_word_pos",
                    shape=[
                        -1, int((image_shape[-2] / 8) * (image_shape[-1] / 8)),
                        1
                    ],
                    dtype="int64")
                gsrm_word_pos = fluid.data(
                    name="gsrm_word_pos",
                    shape=[-1, self.max_text_length, 1],
                    dtype="int64")
                gsrm_slf_attn_bias1 = fluid.data(
                    name="gsrm_slf_attn_bias1",
                    shape=[
                        -1, self.num_heads, self.max_text_length,
                        self.max_text_length
T
tink2123 已提交
168 169
                    ],
                    dtype="float32")
T
tink2123 已提交
170 171 172 173 174
                gsrm_slf_attn_bias2 = fluid.data(
                    name="gsrm_slf_attn_bias2",
                    shape=[
                        -1, self.num_heads, self.max_text_length,
                        self.max_text_length
T
tink2123 已提交
175 176
                    ],
                    dtype="float32")
T
tink2123 已提交
177 178 179 180 181 182
                labels = {
                    'encoder_word_pos': encoder_word_pos,
                    'gsrm_word_pos': gsrm_word_pos,
                    'gsrm_slf_attn_bias1': gsrm_slf_attn_bias1,
                    'gsrm_slf_attn_bias2': gsrm_slf_attn_bias2
                }
T
tink2123 已提交
183

L
LDOUBLEV 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        return image, labels, loader

    def __call__(self, mode):
        image, labels, loader = self.create_feed(mode)
        if self.tps is None:
            inputs = image
        else:
            inputs = self.tps(image)
        conv_feas = self.backbone(inputs)
        predicts = self.head(conv_feas, labels, mode)
        decoded_out = predicts['decoded_out']
        if mode == "train":
            loss = self.loss(predicts, labels)
            if self.loss_type == "attention":
                label = labels['label_out']
            else:
                label = labels['label']
T
tink2123 已提交
201 202
            if self.loss_type == 'srn':
                total_loss, img_loss, word_loss = self.loss(predicts, labels)
T
tink2123 已提交
203 204 205 206 207 208 209
                outputs = {
                    'total_loss': total_loss,
                    'img_loss': img_loss,
                    'word_loss': word_loss,
                    'decoded_out': decoded_out,
                    'label': label
                }
T
tink2123 已提交
210 211 212
            else:
                outputs = {'total_loss':loss, 'decoded_out':\
                    decoded_out, 'label':label}
L
LDOUBLEV 已提交
213
            return loader, outputs
T
tink2123 已提交
214

L
LDOUBLEV 已提交
215
        elif mode == "export":
L
LDOUBLEV 已提交
216
            predict = predicts['predict']
D
dyning 已提交
217 218
            if self.loss_type == "ctc":
                predict = fluid.layers.softmax(predict)
T
tink2123 已提交
219
            if self.loss_type == "srn":
T
tink2123 已提交
220 221 222 223 224 225 226
                return [
                    image, labels, {
                        'decoded_out': decoded_out,
                        'predicts': predict
                    }
                ]

L
LDOUBLEV 已提交
227
            return [image, {'decoded_out': decoded_out, 'predicts': predict}]
L
LDOUBLEV 已提交
228
        else:
D
dyning 已提交
229 230 231
            predict = predicts['predict']
            if self.loss_type == "ctc":
                predict = fluid.layers.softmax(predict)
T
tink2123 已提交
232
            return loader, {'decoded_out': decoded_out, 'predicts': predict}