predict_system.py 9.4 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 30
from copy import deepcopy
from attrdict import AttrDict
W
WenmuZhou 已提交
31 32 33 34

from ppocr.utils.utility import get_image_file_list, check_and_read_gif
from ppocr.utils.logging import get_logger
from tools.infer.predict_system import TextSystem
文幕地方's avatar
文幕地方 已提交
35
from ppstructure.layout.predict_layout import LayoutPredictor
W
WenmuZhou 已提交
36
from ppstructure.table.predict_table import TableSystem, to_excel
37
from ppstructure.utility import parse_args, draw_structure_result
A
update  
an1018 已提交
38
from ppstructure.recovery.recovery_to_doc import convert_info_docx
W
WenmuZhou 已提交
39 40 41 42

logger = get_logger()


43
class StructureSystem(object):
W
WenmuZhou 已提交
44
    def __init__(self, args):
45
        self.mode = args.mode
文幕地方's avatar
文幕地方 已提交
46
        self.recovery = args.recovery
47 48 49
        if self.mode == 'structure':
            if not args.show_log:
                logger.setLevel(logging.INFO)
50 51 52 53 54 55
            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
文幕地方 已提交
56 57
            # init model
            self.layout_predictor = None
58
            self.text_system = None
文幕地方's avatar
文幕地方 已提交
59
            self.table_system = None
60
            if args.layout:
文幕地方's avatar
文幕地方 已提交
61
                self.layout_predictor = LayoutPredictor(args)
62 63 64 65 66 67 68 69 70 71
                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)

72
        elif self.mode == 'vqa':
文幕地方's avatar
文幕地方 已提交
73
            raise NotImplementedError
W
WenmuZhou 已提交
74

75
    def __call__(self, img, return_ocr_result_in_table=False):
文幕地方's avatar
文幕地方 已提交
76 77 78 79 80 81 82 83 84 85
        time_dict = {
            'layout': 0,
            'table': 0,
            'table_match': 0,
            'det': 0,
            'rec': 0,
            'vqa': 0,
            'all': 0
        }
        start = time.time()
86 87
        if self.mode == 'structure':
            ori_im = img.copy()
文幕地方's avatar
文幕地方 已提交
88 89 90
            if self.layout_predictor is not None:
                layout_res, elapse = self.layout_predictor(img)
                time_dict['layout'] += elapse
91 92
            else:
                h, w = ori_im.shape[:2]
文幕地方's avatar
文幕地方 已提交
93
                layout_res = [dict(bbox=None, label='table')]
94 95
            res_list = []
            for region in layout_res:
96
                res = ''
文幕地方's avatar
文幕地方 已提交
97 98 99 100 101 102 103 104
                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':
105
                    if self.table_system is not None:
文幕地方's avatar
文幕地方 已提交
106 107 108 109 110 111
                        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']
112
                else:
113
                    if self.text_system is not None:
文幕地方's avatar
文幕地方 已提交
114
                        if self.recovery:
A
an1018 已提交
115 116
                            wht_im = np.ones(ori_im.shape, dtype=ori_im.dtype)
                            wht_im[y1:y2, x1:x2, :] = roi_img
文幕地方's avatar
文幕地方 已提交
117 118
                            filter_boxes, filter_rec_res, ocr_time_dict = self.text_system(
                                wht_im)
A
an1018 已提交
119
                        else:
文幕地方's avatar
文幕地方 已提交
120 121 122 123
                            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']
124 125 126 127 128 129 130 131 132 133 134 135 136
                        # remove style char
                        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
文幕地方 已提交
137
                            if not self.recovery:
A
an1018 已提交
138
                                box += [x1, y1]
139 140 141 142 143
                            res.append({
                                'text': rec_str,
                                'confidence': float(rec_conf),
                                'text_region': box.tolist()
                            })
144
                res_list.append({
文幕地方's avatar
文幕地方 已提交
145
                    'type': region['label'].lower(),
146 147 148 149
                    'bbox': [x1, y1, x2, y2],
                    'img': roi_img,
                    'res': res
                })
文幕地方's avatar
文幕地方 已提交
150 151 152
            end = time.time()
            time_dict['all'] = end - start
            return res_list, time_dict
153
        elif self.mode == 'vqa':
文幕地方's avatar
文幕地方 已提交
154
            raise NotImplementedError
文幕地方's avatar
文幕地方 已提交
155
        return None, None
W
WenmuZhou 已提交
156

W
WenmuZhou 已提交
157

158
def save_structure_res(res, save_folder, img_name):
W
WenmuZhou 已提交
159 160
    excel_save_folder = os.path.join(save_folder, img_name)
    os.makedirs(excel_save_folder, exist_ok=True)
161
    res_cp = deepcopy(res)
W
WenmuZhou 已提交
162
    # save res
163 164 165
    with open(
            os.path.join(excel_save_folder, 'res.txt'), 'w',
            encoding='utf8') as f:
166 167 168 169
        for region in res_cp:
            roi_img = region.pop('img')
            f.write('{}\n'.format(json.dumps(region)))

文幕地方's avatar
文幕地方 已提交
170
            if region['type'] == 'table' and len(region[
171
                    'res']) > 0 and 'html' in region['res']:
172 173
                excel_path = os.path.join(excel_save_folder,
                                          '{}.xlsx'.format(region['bbox']))
174
                to_excel(region['res']['html'], excel_path)
文幕地方's avatar
文幕地方 已提交
175
            elif region['type'] == 'figure':
176 177
                img_path = os.path.join(excel_save_folder,
                                        '{}.jpg'.format(region['bbox']))
W
WenmuZhou 已提交
178
                cv2.imwrite(img_path, roi_img)
W
WenmuZhou 已提交
179 180 181 182 183 184 185


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]

186
    structure_sys = StructureSystem(args)
W
WenmuZhou 已提交
187
    img_num = len(image_file_list)
188 189 190
    save_folder = os.path.join(args.output, structure_sys.mode)
    os.makedirs(save_folder, exist_ok=True)

W
WenmuZhou 已提交
191 192 193 194 195 196 197 198 199 200 201
    for i, image_file in enumerate(image_file_list):
        logger.info("[{}/{}] {}".format(i, img_num, image_file))
        img, flag = check_and_read_gif(image_file)
        img_name = os.path.basename(image_file).split('.')[0]

        if not flag:
            img = cv2.imread(image_file)
        if img is None:
            logger.error("error in loading image:{}".format(image_file))
            continue
        starttime = time.time()
文幕地方's avatar
文幕地方 已提交
202
        res, time_dict = structure_sys(img)
203 204 205 206 207 208

        if structure_sys.mode == 'structure':
            save_structure_res(res, save_folder, img_name)
            draw_img = draw_structure_result(img, res, args.vis_font_path)
            img_save_path = os.path.join(save_folder, img_name, 'show.jpg')
        elif structure_sys.mode == 'vqa':
文幕地方's avatar
文幕地方 已提交
209 210 211
            raise NotImplementedError
            # draw_img = draw_ser_results(img, res, args.vis_font_path)
            # img_save_path = os.path.join(save_folder, img_name + '.jpg')
212 213
        cv2.imwrite(img_save_path, draw_img)
        logger.info('result save to {}'.format(img_save_path))
A
an1018 已提交
214
        if args.recovery:
文幕地方's avatar
文幕地方 已提交
215
            convert_info_docx(img, res, save_folder, img_name)
W
WenmuZhou 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
        elapse = time.time() - starttime
        logger.info("Predict time : {:.3f}s".format(elapse))


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)