predict_kie_token_ser_re.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. __dir__ = os.path.dirname(os.path.abspath(__file__))
  17. sys.path.append(__dir__)
  18. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "../..")))
  19. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  20. import cv2
  21. import json
  22. import numpy as np
  23. import time
  24. import tools.infer.utility as utility
  25. from tools.infer_kie_token_ser_re import make_input
  26. from ppocr.postprocess import build_post_process
  27. from ppocr.utils.logging import get_logger
  28. from ppocr.utils.visual import draw_ser_results, draw_re_results
  29. from ppocr.utils.utility import get_image_file_list, check_and_read
  30. from ppstructure.utility import parse_args
  31. from ppstructure.kie.predict_kie_token_ser import SerPredictor
  32. logger = get_logger()
  33. class SerRePredictor(object):
  34. def __init__(self, args):
  35. self.use_visual_backbone = args.use_visual_backbone
  36. self.ser_engine = SerPredictor(args)
  37. if args.re_model_dir is not None:
  38. postprocess_params = {"name": "VQAReTokenLayoutLMPostProcess"}
  39. self.postprocess_op = build_post_process(postprocess_params)
  40. (
  41. self.predictor,
  42. self.input_tensor,
  43. self.output_tensors,
  44. self.config,
  45. ) = utility.create_predictor(args, "re", logger)
  46. else:
  47. self.predictor = None
  48. def __call__(self, img):
  49. starttime = time.time()
  50. ser_results, ser_inputs, ser_elapse = self.ser_engine(img)
  51. if self.predictor is None:
  52. return ser_results, ser_elapse
  53. re_input, entity_idx_dict_batch = make_input(ser_inputs, ser_results)
  54. if self.use_visual_backbone == False:
  55. re_input.pop(4)
  56. for idx in range(len(self.input_tensor)):
  57. self.input_tensor[idx].copy_from_cpu(re_input[idx])
  58. self.predictor.run()
  59. outputs = []
  60. for output_tensor in self.output_tensors:
  61. output = output_tensor.copy_to_cpu()
  62. outputs.append(output)
  63. preds = dict(
  64. loss=outputs[1],
  65. pred_relations=outputs[2],
  66. hidden_states=outputs[0],
  67. )
  68. post_result = self.postprocess_op(
  69. preds, ser_results=ser_results, entity_idx_dict_batch=entity_idx_dict_batch
  70. )
  71. elapse = time.time() - starttime
  72. return post_result, elapse
  73. def main(args):
  74. image_file_list = get_image_file_list(args.image_dir)
  75. ser_re_predictor = SerRePredictor(args)
  76. count = 0
  77. total_time = 0
  78. os.makedirs(args.output, exist_ok=True)
  79. with open(
  80. os.path.join(args.output, "infer.txt"), mode="w", encoding="utf-8"
  81. ) as f_w:
  82. for image_file in image_file_list:
  83. img, flag, _ = check_and_read(image_file)
  84. if not flag:
  85. img = cv2.imread(image_file)
  86. img = img[:, :, ::-1]
  87. if img is None:
  88. logger.info("error in loading image:{}".format(image_file))
  89. continue
  90. re_res, elapse = ser_re_predictor(img)
  91. re_res = re_res[0]
  92. res_str = "{}\t{}\n".format(
  93. image_file,
  94. json.dumps(
  95. {
  96. "ocr_info": re_res,
  97. },
  98. ensure_ascii=False,
  99. ),
  100. )
  101. f_w.write(res_str)
  102. if ser_re_predictor.predictor is not None:
  103. img_res = draw_re_results(
  104. image_file, re_res, font_path=args.vis_font_path
  105. )
  106. img_save_path = os.path.join(
  107. args.output,
  108. os.path.splitext(os.path.basename(image_file))[0] + "_ser_re.jpg",
  109. )
  110. else:
  111. img_res = draw_ser_results(
  112. image_file, re_res, font_path=args.vis_font_path
  113. )
  114. img_save_path = os.path.join(
  115. args.output,
  116. os.path.splitext(os.path.basename(image_file))[0] + "_ser.jpg",
  117. )
  118. cv2.imwrite(img_save_path, img_res)
  119. logger.info("save vis result to {}".format(img_save_path))
  120. if count > 0:
  121. total_time += elapse
  122. count += 1
  123. logger.info("Predict time of {}: {}".format(image_file, elapse))
  124. if __name__ == "__main__":
  125. main(parse_args())