predict_kie_token_ser_re.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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. self.predictor, self.input_tensor, self.output_tensors, self.config = \
  41. utility.create_predictor(args, 're', logger)
  42. else:
  43. self.predictor = None
  44. def __call__(self, img):
  45. starttime = time.time()
  46. ser_results, ser_inputs, ser_elapse = self.ser_engine(img)
  47. if self.predictor is None:
  48. return ser_results, ser_elapse
  49. re_input, entity_idx_dict_batch = make_input(ser_inputs, ser_results)
  50. if self.use_visual_backbone == False:
  51. re_input.pop(4)
  52. for idx in range(len(self.input_tensor)):
  53. self.input_tensor[idx].copy_from_cpu(re_input[idx])
  54. self.predictor.run()
  55. outputs = []
  56. for output_tensor in self.output_tensors:
  57. output = output_tensor.copy_to_cpu()
  58. outputs.append(output)
  59. preds = dict(
  60. loss=outputs[1],
  61. pred_relations=outputs[2],
  62. hidden_states=outputs[0], )
  63. post_result = self.postprocess_op(
  64. preds,
  65. ser_results=ser_results,
  66. entity_idx_dict_batch=entity_idx_dict_batch)
  67. elapse = time.time() - starttime
  68. return post_result, elapse
  69. def main(args):
  70. image_file_list = get_image_file_list(args.image_dir)
  71. ser_re_predictor = SerRePredictor(args)
  72. count = 0
  73. total_time = 0
  74. os.makedirs(args.output, exist_ok=True)
  75. with open(
  76. os.path.join(args.output, 'infer.txt'), mode='w',
  77. encoding='utf-8') as f_w:
  78. for image_file in image_file_list:
  79. img, flag, _ = check_and_read(image_file)
  80. if not flag:
  81. img = cv2.imread(image_file)
  82. img = img[:, :, ::-1]
  83. if img is None:
  84. logger.info("error in loading image:{}".format(image_file))
  85. continue
  86. re_res, elapse = ser_re_predictor(img)
  87. re_res = re_res[0]
  88. res_str = '{}\t{}\n'.format(
  89. image_file,
  90. json.dumps(
  91. {
  92. "ocr_info": re_res,
  93. }, ensure_ascii=False))
  94. f_w.write(res_str)
  95. if ser_re_predictor.predictor is not None:
  96. img_res = draw_re_results(
  97. image_file, re_res, font_path=args.vis_font_path)
  98. img_save_path = os.path.join(
  99. args.output,
  100. os.path.splitext(os.path.basename(image_file))[0] +
  101. "_ser_re.jpg")
  102. else:
  103. img_res = draw_ser_results(
  104. image_file, re_res, font_path=args.vis_font_path)
  105. img_save_path = os.path.join(
  106. args.output,
  107. os.path.splitext(os.path.basename(image_file))[0] +
  108. "_ser.jpg")
  109. cv2.imwrite(img_save_path, img_res)
  110. logger.info("save vis result to {}".format(img_save_path))
  111. if count > 0:
  112. total_time += elapse
  113. count += 1
  114. logger.info("Predict time of {}: {}".format(image_file, elapse))
  115. if __name__ == "__main__":
  116. main(parse_args())