predict_kie_token_ser.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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 ppocr.data import create_operators, transform
  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
  29. from ppocr.utils.utility import get_image_file_list, check_and_read
  30. from ppstructure.utility import parse_args
  31. from paddleocr import PaddleOCR
  32. logger = get_logger()
  33. class SerPredictor(object):
  34. def __init__(self, args):
  35. self.ocr_engine = PaddleOCR(
  36. use_angle_cls=args.use_angle_cls,
  37. det_model_dir=args.det_model_dir,
  38. rec_model_dir=args.rec_model_dir,
  39. show_log=False,
  40. use_gpu=args.use_gpu)
  41. pre_process_list = [{
  42. 'VQATokenLabelEncode': {
  43. 'algorithm': args.kie_algorithm,
  44. 'class_path': args.ser_dict_path,
  45. 'contains_re': False,
  46. 'ocr_engine': self.ocr_engine,
  47. 'order_method': args.ocr_order_method,
  48. }
  49. }, {
  50. 'VQATokenPad': {
  51. 'max_seq_len': 512,
  52. 'return_attention_mask': True
  53. }
  54. }, {
  55. 'VQASerTokenChunk': {
  56. 'max_seq_len': 512,
  57. 'return_attention_mask': True
  58. }
  59. }, {
  60. 'Resize': {
  61. 'size': [224, 224]
  62. }
  63. }, {
  64. 'NormalizeImage': {
  65. 'std': [58.395, 57.12, 57.375],
  66. 'mean': [123.675, 116.28, 103.53],
  67. 'scale': '1',
  68. 'order': 'hwc'
  69. }
  70. }, {
  71. 'ToCHWImage': None
  72. }, {
  73. 'KeepKeys': {
  74. 'keep_keys': [
  75. 'input_ids', 'bbox', 'attention_mask', 'token_type_ids',
  76. 'image', 'labels', 'segment_offset_id', 'ocr_info',
  77. 'entities'
  78. ]
  79. }
  80. }]
  81. postprocess_params = {
  82. 'name': 'VQASerTokenLayoutLMPostProcess',
  83. "class_path": args.ser_dict_path,
  84. }
  85. self.preprocess_op = create_operators(pre_process_list,
  86. {'infer_mode': True})
  87. self.postprocess_op = build_post_process(postprocess_params)
  88. self.predictor, self.input_tensor, self.output_tensors, self.config = \
  89. utility.create_predictor(args, 'ser', logger)
  90. def __call__(self, img):
  91. ori_im = img.copy()
  92. data = {'image': img}
  93. data = transform(data, self.preprocess_op)
  94. if data[0] is None:
  95. return None, 0
  96. starttime = time.time()
  97. for idx in range(len(data)):
  98. if isinstance(data[idx], np.ndarray):
  99. data[idx] = np.expand_dims(data[idx], axis=0)
  100. else:
  101. data[idx] = [data[idx]]
  102. for idx in range(len(self.input_tensor)):
  103. self.input_tensor[idx].copy_from_cpu(data[idx])
  104. self.predictor.run()
  105. outputs = []
  106. for output_tensor in self.output_tensors:
  107. output = output_tensor.copy_to_cpu()
  108. outputs.append(output)
  109. preds = outputs[0]
  110. post_result = self.postprocess_op(
  111. preds, segment_offset_ids=data[6], ocr_infos=data[7])
  112. elapse = time.time() - starttime
  113. return post_result, data, elapse
  114. def main(args):
  115. image_file_list = get_image_file_list(args.image_dir)
  116. ser_predictor = SerPredictor(args)
  117. count = 0
  118. total_time = 0
  119. os.makedirs(args.output, exist_ok=True)
  120. with open(
  121. os.path.join(args.output, 'infer.txt'), mode='w',
  122. encoding='utf-8') as f_w:
  123. for image_file in image_file_list:
  124. img, flag, _ = check_and_read(image_file)
  125. if not flag:
  126. img = cv2.imread(image_file)
  127. img = img[:, :, ::-1]
  128. if img is None:
  129. logger.info("error in loading image:{}".format(image_file))
  130. continue
  131. ser_res, _, elapse = ser_predictor(img)
  132. ser_res = ser_res[0]
  133. res_str = '{}\t{}\n'.format(
  134. image_file,
  135. json.dumps(
  136. {
  137. "ocr_info": ser_res,
  138. }, ensure_ascii=False))
  139. f_w.write(res_str)
  140. img_res = draw_ser_results(
  141. image_file,
  142. ser_res,
  143. font_path=args.vis_font_path, )
  144. img_save_path = os.path.join(args.output,
  145. os.path.basename(image_file))
  146. cv2.imwrite(img_save_path, img_res)
  147. logger.info("save vis result to {}".format(img_save_path))
  148. if count > 0:
  149. total_time += elapse
  150. count += 1
  151. logger.info("Predict time of {}: {}".format(image_file, elapse))
  152. if __name__ == "__main__":
  153. main(parse_args())