infer_ser_e2e.py 5.3 KB
Newer Older
littletomatodonkey's avatar
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2021 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
littletomatodonkey's avatar
littletomatodonkey 已提交
17 18 19 20

__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)

littletomatodonkey's avatar
littletomatodonkey 已提交
21 22 23 24 25 26 27 28
import json
import cv2
import numpy as np
from copy import deepcopy
from PIL import Image

import paddle
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer, LayoutXLMForTokenClassification
文幕地方's avatar
文幕地方 已提交
29
from paddlenlp.transformers import LayoutLMModel, LayoutLMTokenizer, LayoutLMForTokenClassification
littletomatodonkey's avatar
littletomatodonkey 已提交
30 31

# relative reference
littletomatodonkey's avatar
littletomatodonkey 已提交
32
from vqa_utils import parse_args, get_image_file_list, draw_ser_results, get_bio_label_maps
littletomatodonkey's avatar
littletomatodonkey 已提交
33

littletomatodonkey's avatar
littletomatodonkey 已提交
34
from vqa_utils import pad_sentences, split_page, preprocess, postprocess, merge_preds_list_with_ocr_info
littletomatodonkey's avatar
littletomatodonkey 已提交
35

Z
zhoujun 已提交
36 37 38 39 40 41
MODELS = {
    'LayoutXLM':
    (LayoutXLMTokenizer, LayoutXLMModel, LayoutXLMForTokenClassification),
    'LayoutLM':
    (LayoutLMTokenizer, LayoutLMModel, LayoutLMForTokenClassification)
}
littletomatodonkey's avatar
littletomatodonkey 已提交
42

文幕地方's avatar
文幕地方 已提交
43 44 45 46 47 48 49
MODELS = {
    'LayoutXLM':
    (LayoutXLMTokenizer, LayoutXLMModel, LayoutXLMForTokenClassification),
    'LayoutLM':
    (LayoutLMTokenizer, LayoutLMModel, LayoutLMForTokenClassification)
}

littletomatodonkey's avatar
littletomatodonkey 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

def trans_poly_to_bbox(poly):
    x1 = np.min([p[0] for p in poly])
    x2 = np.max([p[0] for p in poly])
    y1 = np.min([p[1] for p in poly])
    y2 = np.max([p[1] for p in poly])
    return [x1, y1, x2, y2]


def parse_ocr_info_for_ser(ocr_result):
    ocr_info = []
    for res in ocr_result:
        ocr_info.append({
            "text": res[1][0],
            "bbox": trans_poly_to_bbox(res[0]),
            "poly": res[0],
        })
    return ocr_info


文幕地方's avatar
add re  
文幕地方 已提交
70 71
class SerPredictor(object):
    def __init__(self, args):
文幕地方's avatar
文幕地方 已提交
72
        self.args = args
文幕地方's avatar
add re  
文幕地方 已提交
73 74 75
        self.max_seq_length = args.max_seq_length

        # init ser token and model
文幕地方's avatar
文幕地方 已提交
76 77 78
        tokenizer_class, base_model_class, model_class = MODELS[
            args.ser_model_type]
        self.tokenizer = tokenizer_class.from_pretrained(
文幕地方's avatar
add re  
文幕地方 已提交
79
            args.model_name_or_path)
文幕地方's avatar
文幕地方 已提交
80
        self.model = model_class.from_pretrained(args.model_name_or_path)
文幕地方's avatar
add re  
文幕地方 已提交
81 82 83
        self.model.eval()

        # init ocr_engine
84 85
        from paddleocr import PaddleOCR

文幕地方's avatar
add re  
文幕地方 已提交
86
        self.ocr_engine = PaddleOCR(
87 88
            rec_model_dir=args.rec_model_dir,
            det_model_dir=args.det_model_dir,
文幕地方's avatar
add re  
文幕地方 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
            use_angle_cls=False,
            show_log=False)
        # init dict
        label2id_map, self.id2label_map = get_bio_label_maps(
            args.label_map_path)
        self.label2id_map_for_draw = dict()
        for key in label2id_map:
            if key.startswith("I-"):
                self.label2id_map_for_draw[key] = label2id_map["B" + key[1:]]
            else:
                self.label2id_map_for_draw[key] = label2id_map[key]

    def __call__(self, img):
        ocr_result = self.ocr_engine.ocr(img, cls=False)

        ocr_info = parse_ocr_info_for_ser(ocr_result)

        inputs = preprocess(
            tokenizer=self.tokenizer,
            ori_img=img,
            ocr_info=ocr_info,
            max_seq_len=self.max_seq_length)

文幕地方's avatar
文幕地方 已提交
112
        if self.args.ser_model_type == 'LayoutLM':
文幕地方's avatar
文幕地方 已提交
113 114 115 116 117
            preds = self.model(
                input_ids=inputs["input_ids"],
                bbox=inputs["bbox"],
                token_type_ids=inputs["token_type_ids"],
                attention_mask=inputs["attention_mask"])
文幕地方's avatar
文幕地方 已提交
118
        elif self.args.ser_model_type == 'LayoutXLM':
文幕地方's avatar
文幕地方 已提交
119 120 121 122 123 124 125
            preds = self.model(
                input_ids=inputs["input_ids"],
                bbox=inputs["bbox"],
                image=inputs["image"],
                token_type_ids=inputs["token_type_ids"],
                attention_mask=inputs["attention_mask"])
            preds = preds[0]
文幕地方's avatar
add re  
文幕地方 已提交
126 127 128 129 130 131

        preds = postprocess(inputs["attention_mask"], preds, self.id2label_map)
        ocr_info = merge_preds_list_with_ocr_info(
            ocr_info, inputs["segment_offset_id"], preds,
            self.label2id_map_for_draw)
        return ocr_info, inputs
littletomatodonkey's avatar
littletomatodonkey 已提交
132 133


文幕地方's avatar
add re  
文幕地方 已提交
134 135 136
if __name__ == "__main__":
    args = parse_args()
    os.makedirs(args.output_dir, exist_ok=True)
littletomatodonkey's avatar
littletomatodonkey 已提交
137 138 139 140 141

    # get infer img list
    infer_imgs = get_image_file_list(args.infer_imgs)

    # loop for infer
文幕地方's avatar
add re  
文幕地方 已提交
142
    ser_engine = SerPredictor(args)
文幕地方's avatar
文幕地方 已提交
143 144 145 146
    with open(
            os.path.join(args.output_dir, "infer_results.txt"),
            "w",
            encoding='utf-8') as fout:
littletomatodonkey's avatar
littletomatodonkey 已提交
147
        for idx, img_path in enumerate(infer_imgs):
文幕地方's avatar
文幕地方 已提交
148 149 150
            save_img_path = os.path.join(
                args.output_dir,
                os.path.splitext(os.path.basename(img_path))[0] + "_ser.jpg")
文幕地方's avatar
rm _  
文幕地方 已提交
151
            print("process: [{}/{}], save result to {}".format(
文幕地方's avatar
文幕地方 已提交
152
                idx, len(infer_imgs), save_img_path))
littletomatodonkey's avatar
littletomatodonkey 已提交
153 154 155

            img = cv2.imread(img_path)

文幕地方's avatar
add re  
文幕地方 已提交
156
            result, _ = ser_engine(img)
littletomatodonkey's avatar
littletomatodonkey 已提交
157 158
            fout.write(img_path + "\t" + json.dumps(
                {
文幕地方's avatar
add re  
文幕地方 已提交
159
                    "ser_resule": result,
littletomatodonkey's avatar
littletomatodonkey 已提交
160 161
                }, ensure_ascii=False) + "\n")

文幕地方's avatar
add re  
文幕地方 已提交
162
            img_res = draw_ser_results(img, result)
文幕地方's avatar
文幕地方 已提交
163
            cv2.imwrite(save_img_path, img_res)