predict_system.py 11.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 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.

import os
import sys
import subprocess

__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
文幕地方's avatar
文幕地方 已提交
21
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../')))
W
WenmuZhou 已提交
22 23 24

os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
import cv2
文幕地方's avatar
文幕地方 已提交
25
import json
A
an1018 已提交
26
import numpy as np
W
WenmuZhou 已提交
27
import time
W
WenmuZhou 已提交
28
import logging
29
from copy import deepcopy
W
WenmuZhou 已提交
30

U
user1018 已提交
31
from ppocr.utils.utility import get_image_file_list, check_and_read
W
WenmuZhou 已提交
32 33
from ppocr.utils.logging import get_logger
from tools.infer.predict_system import TextSystem
文幕地方's avatar
文幕地方 已提交
34
from ppstructure.layout.predict_layout import LayoutPredictor
W
WenmuZhou 已提交
35
from ppstructure.table.predict_table import TableSystem, to_excel
36
from ppstructure.utility import parse_args, draw_structure_result
W
WenmuZhou 已提交
37 38 39 40

logger = get_logger()


41
class StructureSystem(object):
W
WenmuZhou 已提交
42
    def __init__(self, args):
43
        self.mode = args.mode
文幕地方's avatar
文幕地方 已提交
44
        self.recovery = args.recovery
45 46 47 48 49 50 51

        self.image_orientation_predictor = None
        if args.image_orientation:
            import paddleclas
            self.image_orientation_predictor = paddleclas.PaddleClas(
                model_name="text_image_orientation")

52 53 54
        if self.mode == 'structure':
            if not args.show_log:
                logger.setLevel(logging.INFO)
55 56 57 58 59 60
            if args.layout == False and args.ocr == True:
                args.ocr = False
                logger.warning(
                    "When args.layout is false, args.ocr is automatically set to false"
                )
            args.drop_score = 0
文幕地方's avatar
文幕地方 已提交
61 62
            # init model
            self.layout_predictor = None
63
            self.text_system = None
文幕地方's avatar
文幕地方 已提交
64
            self.table_system = None
65
            if args.layout:
文幕地方's avatar
文幕地方 已提交
66
                self.layout_predictor = LayoutPredictor(args)
67 68 69 70 71 72 73 74 75 76
                if args.ocr:
                    self.text_system = TextSystem(args)
            if args.table:
                if self.text_system is not None:
                    self.table_system = TableSystem(
                        args, self.text_system.text_detector,
                        self.text_system.text_recognizer)
                else:
                    self.table_system = TableSystem(args)

77
        elif self.mode == 'kie':
文幕地方's avatar
文幕地方 已提交
78
            raise NotImplementedError
W
WenmuZhou 已提交
79

A
an1018 已提交
80
    def __call__(self, img, return_ocr_result_in_table=False, img_idx=0):
文幕地方's avatar
文幕地方 已提交
81
        time_dict = {
82
            'image_orientation': 0,
文幕地方's avatar
文幕地方 已提交
83 84 85 86 87
            'layout': 0,
            'table': 0,
            'table_match': 0,
            'det': 0,
            'rec': 0,
88
            'kie': 0,
文幕地方's avatar
文幕地方 已提交
89 90 91
            'all': 0
        }
        start = time.time()
92 93 94 95 96 97 98 99 100 101 102
        if self.image_orientation_predictor is not None:
            tic = time.time()
            cls_result = self.image_orientation_predictor.predict(
                input_data=img)
            cls_res = next(cls_result)
            angle = cls_res[0]['label_names'][0]
            cv_rotate_code = {
                '90': cv2.ROTATE_90_COUNTERCLOCKWISE,
                '180': cv2.ROTATE_180,
                '270': cv2.ROTATE_90_CLOCKWISE
            }
文幕地方's avatar
文幕地方 已提交
103 104
            if angle in cv_rotate_code:
                img = cv2.rotate(img, cv_rotate_code[angle])
105 106
            toc = time.time()
            time_dict['image_orientation'] = toc - tic
107 108
        if self.mode == 'structure':
            ori_im = img.copy()
文幕地方's avatar
文幕地方 已提交
109 110 111
            if self.layout_predictor is not None:
                layout_res, elapse = self.layout_predictor(img)
                time_dict['layout'] += elapse
112 113
            else:
                h, w = ori_im.shape[:2]
文幕地方's avatar
文幕地方 已提交
114
                layout_res = [dict(bbox=None, label='table')]
115 116
            res_list = []
            for region in layout_res:
117
                res = ''
文幕地方's avatar
文幕地方 已提交
118 119 120 121 122 123 124 125
                if region['bbox'] is not None:
                    x1, y1, x2, y2 = region['bbox']
                    x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
                    roi_img = ori_im[y1:y2, x1:x2, :]
                else:
                    x1, y1, x2, y2 = 0, 0, w, h
                    roi_img = ori_im
                if region['label'] == 'table':
126
                    if self.table_system is not None:
文幕地方's avatar
文幕地方 已提交
127 128 129 130 131 132
                        res, table_time_dict = self.table_system(
                            roi_img, return_ocr_result_in_table)
                        time_dict['table'] += table_time_dict['table']
                        time_dict['table_match'] += table_time_dict['match']
                        time_dict['det'] += table_time_dict['det']
                        time_dict['rec'] += table_time_dict['rec']
133
                else:
134
                    if self.text_system is not None:
文幕地方's avatar
文幕地方 已提交
135
                        if self.recovery:
A
an1018 已提交
136 137
                            wht_im = np.ones(ori_im.shape, dtype=ori_im.dtype)
                            wht_im[y1:y2, x1:x2, :] = roi_img
文幕地方's avatar
文幕地方 已提交
138 139
                            filter_boxes, filter_rec_res, ocr_time_dict = self.text_system(
                                wht_im)
A
an1018 已提交
140
                        else:
文幕地方's avatar
文幕地方 已提交
141 142 143 144
                            filter_boxes, filter_rec_res, ocr_time_dict = self.text_system(
                                roi_img)
                        time_dict['det'] += ocr_time_dict['det']
                        time_dict['rec'] += ocr_time_dict['rec']
145

U
user1018 已提交
146 147
                        # remove style char,
                        # when using the recognition model trained on the PubtabNet dataset,
148
                        # it will recognize the text format in the table, such as <b>
149 150 151 152 153 154 155 156 157 158 159 160
                        style_token = [
                            '<strike>', '<strike>', '<sup>', '</sub>', '<b>',
                            '</b>', '<sub>', '</sup>', '<overline>',
                            '</overline>', '<underline>', '</underline>', '<i>',
                            '</i>'
                        ]
                        res = []
                        for box, rec_res in zip(filter_boxes, filter_rec_res):
                            rec_str, rec_conf = rec_res
                            for token in style_token:
                                if token in rec_str:
                                    rec_str = rec_str.replace(token, '')
文幕地方's avatar
文幕地方 已提交
161
                            if not self.recovery:
A
an1018 已提交
162
                                box += [x1, y1]
163 164 165 166 167
                            res.append({
                                'text': rec_str,
                                'confidence': float(rec_conf),
                                'text_region': box.tolist()
                            })
168
                res_list.append({
文幕地方's avatar
文幕地方 已提交
169
                    'type': region['label'].lower(),
170 171
                    'bbox': [x1, y1, x2, y2],
                    'img': roi_img,
U
user1018 已提交
172 173
                    'res': res,
                    'img_idx': img_idx
174
                })
文幕地方's avatar
文幕地方 已提交
175 176 177
            end = time.time()
            time_dict['all'] = end - start
            return res_list, time_dict
178
        elif self.mode == 'kie':
文幕地方's avatar
文幕地方 已提交
179
            raise NotImplementedError
文幕地方's avatar
文幕地方 已提交
180
        return None, None
W
WenmuZhou 已提交
181

W
WenmuZhou 已提交
182

U
user1018 已提交
183
def save_structure_res(res, save_folder, img_name, img_idx=0):
W
WenmuZhou 已提交
184 185
    excel_save_folder = os.path.join(save_folder, img_name)
    os.makedirs(excel_save_folder, exist_ok=True)
186
    res_cp = deepcopy(res)
W
WenmuZhou 已提交
187
    # save res
188
    with open(
U
user1018 已提交
189 190
            os.path.join(excel_save_folder, 'res_{}.txt'.format(img_idx)),
            'w',
191
            encoding='utf8') as f:
192 193 194 195
        for region in res_cp:
            roi_img = region.pop('img')
            f.write('{}\n'.format(json.dumps(region)))

U
user1018 已提交
196
            if region['type'].lower() == 'table' and len(region[
197
                    'res']) > 0 and 'html' in region['res']:
U
user1018 已提交
198 199 200
                excel_path = os.path.join(
                    excel_save_folder,
                    '{}_{}.xlsx'.format(region['bbox'], img_idx))
201
                to_excel(region['res']['html'], excel_path)
U
user1018 已提交
202 203 204 205
            elif region['type'].lower() == 'figure':
                img_path = os.path.join(
                    excel_save_folder,
                    '{}_{}.jpg'.format(region['bbox'], img_idx))
W
WenmuZhou 已提交
206
                cv2.imwrite(img_path, roi_img)
W
WenmuZhou 已提交
207 208 209 210 211 212 213


def main(args):
    image_file_list = get_image_file_list(args.image_dir)
    image_file_list = image_file_list
    image_file_list = image_file_list[args.process_id::args.total_process_num]

214
    structure_sys = StructureSystem(args)
W
WenmuZhou 已提交
215
    img_num = len(image_file_list)
216 217 218
    save_folder = os.path.join(args.output, structure_sys.mode)
    os.makedirs(save_folder, exist_ok=True)

W
WenmuZhou 已提交
219 220
    for i, image_file in enumerate(image_file_list):
        logger.info("[{}/{}] {}".format(i, img_num, image_file))
U
user1018 已提交
221
        img, flag_gif, flag_pdf = check_and_read(image_file)
W
WenmuZhou 已提交
222 223
        img_name = os.path.basename(image_file).split('.')[0]

U
user1018 已提交
224
        if not flag_gif and not flag_pdf:
W
WenmuZhou 已提交
225
            img = cv2.imread(image_file)
226

U
user1018 已提交
227 228 229 230
        if not flag_pdf:
            if img is None:
                logger.error("error in loading image:{}".format(image_file))
                continue
A
an1018 已提交
231 232 233
            imgs = [img]
        else:
            imgs = img
U
user1018 已提交
234

A
an1018 已提交
235 236 237 238 239
        all_res = []
        for index, img in enumerate(imgs):
            res, time_dict = structure_sys(img, img_idx=index)
            if structure_sys.mode == 'structure' and res != []:
                save_structure_res(res, save_folder, img_name, index)
U
user1018 已提交
240
                draw_img = draw_structure_result(img, res, args.vis_font_path)
A
an1018 已提交
241 242
                img_save_path = os.path.join(save_folder, img_name,
                                             'show_{}.jpg'.format(index))
243
            elif structure_sys.mode == 'kie':
U
user1018 已提交
244 245 246
                raise NotImplementedError
                # draw_img = draw_ser_results(img, res, args.vis_font_path)
                # img_save_path = os.path.join(save_folder, img_name + '.jpg')
A
an1018 已提交
247 248 249 250 251 252 253 254
            if res != []:
                cv2.imwrite(img_save_path, draw_img)
                logger.info('result save to {}'.format(img_save_path))
            if args.recovery and res != []:
                from ppstructure.recovery.recovery_to_doc import sorted_layout_boxes, convert_info_docx
                h, w, _ = img.shape
                res = sorted_layout_boxes(res, w)
                all_res += res
U
user1018 已提交
255

A
an1018 已提交
256 257
        if args.recovery and all_res != []:
            try:
U
user1018 已提交
258
                convert_info_docx(img, all_res, save_folder, img_name)
A
an1018 已提交
259 260 261 262
            except Exception as ex:
                logger.error("error in layout recovery image:{}, err msg: {}".
                             format(image_file, ex))
                continue
263
        logger.info("Predict time : {:.3f}s".format(time_dict['all']))
W
WenmuZhou 已提交
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281


if __name__ == "__main__":
    args = parse_args()
    if args.use_mp:
        p_list = []
        total_process_num = args.total_process_num
        for process_id in range(total_process_num):
            cmd = [sys.executable, "-u"] + sys.argv + [
                "--process_id={}".format(process_id),
                "--use_mp={}".format(False)
            ]
            p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stdout)
            p_list.append(p)
        for p in p_list:
            p.wait()
    else:
        main(args)