predict_system.py 7.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 21 22 23 24 25 26
# 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__)
sys.path.append(os.path.abspath(os.path.join(__dir__, '..')))

os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
import cv2
import numpy as np
import time
W
WenmuZhou 已提交
27
import logging
W
WenmuZhou 已提交
28 29 30 31

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
W
WenmuZhou 已提交
32
from ppstructure.table.predict_table import TableSystem, to_excel
33
from ppstructure.utility import parse_args, draw_structure_result
W
WenmuZhou 已提交
34 35 36 37

logger = get_logger()


38
class StructureSystem(object):
W
WenmuZhou 已提交
39
    def __init__(self, args):
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
        self.mode = args.mode
        if self.mode == 'structure':
            import layoutparser as lp
            # args.det_limit_type = 'resize_long'
            args.drop_score = 0
            if not args.show_log:
                logger.setLevel(logging.INFO)
            self.text_system = TextSystem(args)
            self.table_system = TableSystem(args,
                                            self.text_system.text_detector,
                                            self.text_system.text_recognizer)

            config_path = None
            model_path = None
            if os.path.isdir(args.layout_path_model):
                model_path = args.layout_path_model
            else:
                config_path = args.layout_path_model
            self.table_layout = lp.PaddleDetectionLayoutModel(
                config_path=config_path,
                model_path=model_path,
文幕地方's avatar
文幕地方 已提交
61
                label_map=args.layout_label_map,
62 63 64 65 66 67 68
                threshold=0.5,
                enable_mkldnn=args.enable_mkldnn,
                enforce_cpu=not args.use_gpu,
                thread_num=args.cpu_threads)
            self.use_angle_cls = args.use_angle_cls
            self.drop_score = args.drop_score
        elif self.mode == 'vqa':
文幕地方's avatar
文幕地方 已提交
69
            from ppstructure.vqa.infer_ser_e2e import SerPredictor, draw_ser_results
70
            self.vqa_engine = SerPredictor(args)
W
WenmuZhou 已提交
71 72

    def __call__(self, img):
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        if self.mode == 'structure':
            ori_im = img.copy()
            layout_res = self.table_layout.detect(img[..., ::-1])
            res_list = []
            for region in layout_res:
                x1, y1, x2, y2 = region.coordinates
                x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
                roi_img = ori_im[y1:y2, x1:x2, :]
                if region.type == 'Table':
                    res = self.table_system(roi_img)
                else:
                    filter_boxes, filter_rec_res = self.text_system(roi_img)
                    filter_boxes = [x + [x1, y1] for x in filter_boxes]
                    filter_boxes = [
                        x.reshape(-1).tolist() for x in filter_boxes
                    ]
                    # remove style char
                    style_token = [
                        '<strike>', '<strike>', '<sup>', '</sub>', '<b>',
                        '</b>', '<sub>', '</sup>', '<overline>', '</overline>',
                        '<underline>', '</underline>', '<i>', '</i>'
                    ]
                    filter_rec_res_tmp = []
                    for rec_res in 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, '')
                        filter_rec_res_tmp.append((rec_str, rec_conf))
                    res = (filter_boxes, filter_rec_res_tmp)
                res_list.append({
                    'type': region.type,
                    'bbox': [x1, y1, x2, y2],
                    'img': roi_img,
                    'res': res
                })
        elif self.mode == 'vqa':
            res_list, _ = self.vqa_engine(img)
W
WenmuZhou 已提交
111 112
        return res_list

W
WenmuZhou 已提交
113

114
def save_structure_res(res, save_folder, img_name):
W
WenmuZhou 已提交
115 116 117
    excel_save_folder = os.path.join(save_folder, img_name)
    os.makedirs(excel_save_folder, exist_ok=True)
    # save res
118 119 120
    with open(
            os.path.join(excel_save_folder, 'res.txt'), 'w',
            encoding='utf8') as f:
W
WenmuZhou 已提交
121 122
        for region in res:
            if region['type'] == 'Table':
123 124
                excel_path = os.path.join(excel_save_folder,
                                          '{}.xlsx'.format(region['bbox']))
W
WenmuZhou 已提交
125
                to_excel(region['res'], excel_path)
W
WenmuZhou 已提交
126 127
            if region['type'] == 'Figure':
                roi_img = region['img']
128 129
                img_path = os.path.join(excel_save_folder,
                                        '{}.jpg'.format(region['bbox']))
W
WenmuZhou 已提交
130
                cv2.imwrite(img_path, roi_img)
W
WenmuZhou 已提交
131
            else:
W
WenmuZhou 已提交
132
                for box, rec_res in zip(region['res'][0], region['res'][1]):
133 134
                    f.write('{}\t{}\n'.format(
                        np.array(box).reshape(-1).tolist(), rec_res))
W
WenmuZhou 已提交
135 136 137 138 139 140 141


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]

142
    structure_sys = StructureSystem(args)
W
WenmuZhou 已提交
143
    img_num = len(image_file_list)
144 145 146
    save_folder = os.path.join(args.output, structure_sys.mode)
    os.makedirs(save_folder, exist_ok=True)

W
WenmuZhou 已提交
147 148 149 150 151 152 153 154 155 156 157 158
    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()
        res = structure_sys(img)
159 160 161 162 163 164 165 166 167 168

        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':
            draw_img = draw_ser_results(img, res, args.vis_font_path)
            img_save_path = os.path.join(save_folder, img_name + '.jpg')
        cv2.imwrite(img_save_path, draw_img)
        logger.info('result save to {}'.format(img_save_path))
W
WenmuZhou 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        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)