predict_table.py 9.1 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 22
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '..')))
sys.path.insert(0, os.path.abspath(os.path.join(__dir__, '../..')))
W
WenmuZhou 已提交
23 24 25 26

os.environ["FLAGS_allocator_strategy"] = 'auto_growth'
import cv2
import copy
文幕地方's avatar
文幕地方 已提交
27
import logging
W
WenmuZhou 已提交
28 29 30 31
import numpy as np
import time
import tools.infer.predict_rec as predict_rec
import tools.infer.predict_det as predict_det
A
andyjpaddle 已提交
32
import tools.infer.utility as utility
文幕地方's avatar
文幕地方 已提交
33
from tools.infer.predict_system import sorted_boxes
34
from ppocr.utils.utility import get_image_file_list, check_and_read
W
WenmuZhou 已提交
35
from ppocr.utils.logging import get_logger
文幕地方's avatar
文幕地方 已提交
36 37
from ppstructure.table.matcher import TableMatch
from ppstructure.table.table_master_match import TableMasterMatcher
W
WenmuZhou 已提交
38 39
from ppstructure.utility import parse_args
import ppstructure.table.predict_structure as predict_strture
W
WenmuZhou 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

logger = get_logger()


def expand(pix, det_box, shape):
    x0, y0, x1, y1 = det_box
    #     print(shape)
    h, w, c = shape
    tmp_x0 = x0 - pix
    tmp_x1 = x1 + pix
    tmp_y0 = y0 - pix
    tmp_y1 = y1 + pix
    x0_ = tmp_x0 if tmp_x0 >= 0 else 0
    x1_ = tmp_x1 if tmp_x1 <= w else w
    y0_ = tmp_y0 if tmp_y0 >= 0 else 0
    y1_ = tmp_y1 if tmp_y1 <= h else h
    return x0_, y0_, x1_, y1_


class TableSystem(object):
    def __init__(self, args, text_detector=None, text_recognizer=None):
文幕地方's avatar
文幕地方 已提交
61
        self.args = args
文幕地方's avatar
文幕地方 已提交
62 63 64
        if not args.show_log:
            logger.setLevel(logging.INFO)

65 66 67 68
        self.text_detector = predict_det.TextDetector(
            args) if text_detector is None else text_detector
        self.text_recognizer = predict_rec.TextRecognizer(
            args) if text_recognizer is None else text_recognizer
文幕地方's avatar
文幕地方 已提交
69

W
WenmuZhou 已提交
70
        self.table_structurer = predict_strture.TableStructurer(args)
文幕地方's avatar
文幕地方 已提交
71 72 73
        if args.table_algorithm in ['TableMaster']:
            self.match = TableMasterMatcher()
        else:
文幕地方's avatar
文幕地方 已提交
74
            self.match = TableMatch(filter_ocr_result=True)
文幕地方's avatar
文幕地方 已提交
75

A
andyjpaddle 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
        self.benchmark = args.benchmark
        self.predictor, self.input_tensor, self.output_tensors, self.config = utility.create_predictor(
            args, 'table', logger)
        if args.benchmark:
            import auto_log
            pid = os.getpid()
            gpu_id = utility.get_infer_gpuid()
            self.autolog = auto_log.AutoLogger(
                model_name="table",
                model_precision=args.precision,
                batch_size=1,
                data_shape="dynamic",
                save_path=None,  #args.save_log_path,
                inference_config=self.config,
                pids=pid,
                process_name=None,
                gpu_ids=gpu_id if args.use_gpu else None,
                time_keys=[
                    'preprocess_time', 'inference_time', 'postprocess_time'
                ],
                warmup=0,
                logger=logger)
W
WenmuZhou 已提交
98

99 100
    def __call__(self, img, return_ocr_result_in_table=False):
        result = dict()
文幕地方's avatar
文幕地方 已提交
101 102
        time_dict = {'det': 0, 'rec': 0, 'table': 0, 'all': 0, 'match': 0}
        start = time.time()
文幕地方's avatar
文幕地方 已提交
103 104
        if self.args.benchmark:
            self.autolog.times.start()
文幕地方's avatar
文幕地方 已提交
105
        structure_res, elapse = self._structure(copy.deepcopy(img))
文幕地方's avatar
文幕地方 已提交
106 107
        if self.benchmark:
            self.autolog.times.stamp()
文幕地方's avatar
文幕地方 已提交
108
        result['cell_bbox'] = structure_res[1].tolist()
文幕地方's avatar
文幕地方 已提交
109 110 111 112
        time_dict['table'] = elapse

        dt_boxes, rec_res, det_elapse, rec_elapse = self._ocr(
            copy.deepcopy(img))
文幕地方's avatar
文幕地方 已提交
113 114
        if self.benchmark:
            self.autolog.times.stamp()
文幕地方's avatar
文幕地方 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
        time_dict['det'] = det_elapse
        time_dict['rec'] = rec_elapse

        if return_ocr_result_in_table:
            result['boxes'] = dt_boxes  #[x.tolist() for x in dt_boxes]
            result['rec_res'] = rec_res

        tic = time.time()
        pred_html = self.match(structure_res, dt_boxes, rec_res)
        toc = time.time()
        time_dict['match'] = toc - tic
        result['html'] = pred_html
        end = time.time()
        time_dict['all'] = end - start
        if self.benchmark:
文幕地方's avatar
文幕地方 已提交
130
            self.autolog.times.end(stamp=True)
文幕地方's avatar
文幕地方 已提交
131 132 133
        return result, time_dict

    def _structure(self, img):
W
WenmuZhou 已提交
134
        structure_res, elapse = self.table_structurer(copy.deepcopy(img))
文幕地方's avatar
文幕地方 已提交
135 136 137
        return structure_res, elapse

    def _ocr(self, img):
文幕地方's avatar
文幕地方 已提交
138
        h, w = img.shape[:2]
文幕地方's avatar
文幕地方 已提交
139
        dt_boxes, det_elapse = self.text_detector(copy.deepcopy(img))
W
WenmuZhou 已提交
140
        dt_boxes = sorted_boxes(dt_boxes)
文幕地方's avatar
文幕地方 已提交
141

W
WenmuZhou 已提交
142 143
        r_boxes = []
        for box in dt_boxes:
文幕地方's avatar
文幕地方 已提交
144 145 146 147
            x_min = max(0, box[:, 0].min() - 1)
            x_max = min(w, box[:, 0].max() + 1)
            y_min = max(0, box[:, 1].min() - 1)
            y_max = min(h, box[:, 1].max() + 1)
W
WenmuZhou 已提交
148 149 150 151
            box = [x_min, y_min, x_max, y_max]
            r_boxes.append(box)
        dt_boxes = np.array(r_boxes)
        logger.debug("dt_boxes num : {}, elapse : {}".format(
文幕地方's avatar
文幕地方 已提交
152
            len(dt_boxes), det_elapse))
W
WenmuZhou 已提交
153 154
        if dt_boxes is None:
            return None, None
文幕地方's avatar
文幕地方 已提交
155

W
WenmuZhou 已提交
156 157 158
        img_crop_list = []
        for i in range(len(dt_boxes)):
            det_box = dt_boxes[i]
文幕地方's avatar
文幕地方 已提交
159 160
            x0, y0, x1, y1 = expand(2, det_box, img.shape)
            text_rect = img[int(y0):int(y1), int(x0):int(x1), :]
W
WenmuZhou 已提交
161
            img_crop_list.append(text_rect)
文幕地方's avatar
文幕地方 已提交
162
        rec_res, rec_elapse = self.text_recognizer(img_crop_list)
W
WenmuZhou 已提交
163
        logger.debug("rec_res num  : {}, elapse : {}".format(
文幕地方's avatar
文幕地方 已提交
164 165
            len(rec_res), rec_elapse))
        return dt_boxes, rec_res, det_elapse, rec_elapse
W
WenmuZhou 已提交
166 167 168 169 170 171 172 173 174 175 176 177


def to_excel(html_table, excel_path):
    from tablepyxl import tablepyxl
    tablepyxl.document_to_xl(html_table, excel_path)


def main(args):
    image_file_list = get_image_file_list(args.image_dir)
    image_file_list = image_file_list[args.process_id::args.total_process_num]
    os.makedirs(args.output, exist_ok=True)

文幕地方's avatar
文幕地方 已提交
178
    table_sys = TableSystem(args)
W
WenmuZhou 已提交
179
    img_num = len(image_file_list)
文幕地方's avatar
文幕地方 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

    f_html = open(
        os.path.join(args.output, 'show.html'), mode='w', encoding='utf-8')
    f_html.write('<html>\n<body>\n')
    f_html.write('<table border="1">\n')
    f_html.write(
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
    )
    f_html.write("<tr>\n")
    f_html.write('<td>img name\n')
    f_html.write('<td>ori image</td>')
    f_html.write('<td>table html</td>')
    f_html.write('<td>cell box</td>')
    f_html.write("</tr>\n")

W
WenmuZhou 已提交
195 196
    for i, image_file in enumerate(image_file_list):
        logger.info("[{}/{}] {}".format(i, img_num, image_file))
197
        img, flag, _ = check_and_read(image_file)
198 199
        excel_path = os.path.join(
            args.output, os.path.basename(image_file).split('.')[0] + '.xlsx')
W
WenmuZhou 已提交
200 201 202 203 204 205
        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
文幕地方 已提交
206
        pred_res, _ = table_sys(img)
207 208
        pred_html = pred_res['html']
        logger.info(pred_html)
W
WenmuZhou 已提交
209 210 211 212
        to_excel(pred_html, excel_path)
        logger.info('excel saved to {}'.format(excel_path))
        elapse = time.time() - starttime
        logger.info("Predict time : {:.3f}s".format(elapse))
文幕地方's avatar
文幕地方 已提交
213

文幕地方's avatar
文幕地方 已提交
214 215 216 217 218 219
        if len(pred_res['cell_bbox']) > 0 and len(pred_res['cell_bbox'][
                0]) == 4:
            img = predict_strture.draw_rectangle(image_file,
                                                 pred_res['cell_bbox'])
        else:
            img = utility.draw_boxes(img, pred_res['cell_bbox'])
文幕地方's avatar
文幕地方 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        img_save_path = os.path.join(args.output, os.path.basename(image_file))
        cv2.imwrite(img_save_path, img)

        f_html.write("<tr>\n")
        f_html.write(f'<td> {os.path.basename(image_file)} <br/>\n')
        f_html.write(f'<td><img src="{image_file}" width=640></td>\n')
        f_html.write('<td><table  border="1">' + pred_html.replace(
            '<html><body><table>', '').replace('</table></body></html>', '') +
                     '</table></td>\n')
        f_html.write(
            f'<td><img src="{os.path.basename(image_file)}" width=640></td>\n')
        f_html.write("</tr>\n")
    f_html.write("</table>\n")
    f_html.close()

A
andyjpaddle 已提交
235
    if args.benchmark:
文幕地方's avatar
文幕地方 已提交
236
        table_sys.autolog.report()
W
WenmuZhou 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254


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)