test_hubserving.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # Copyright (c) 2020 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.append(os.path.abspath(os.path.join(__dir__, "..")))
  19. from ppocr.utils.logging import get_logger
  20. logger = get_logger()
  21. import cv2
  22. import numpy as np
  23. import time
  24. from PIL import Image
  25. from ppocr.utils.utility import get_image_file_list
  26. from tools.infer.utility import draw_ocr, draw_boxes, str2bool
  27. from ppstructure.utility import draw_structure_result
  28. from ppstructure.predict_system import to_excel
  29. import requests
  30. import json
  31. import base64
  32. def cv2_to_base64(image):
  33. return base64.b64encode(image).decode("utf8")
  34. def draw_server_result(image_file, res):
  35. img = cv2.imread(image_file)
  36. image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
  37. if len(res) == 0:
  38. return np.array(image)
  39. keys = res[0].keys()
  40. if "text_region" not in keys: # for ocr_rec, draw function is invalid
  41. logger.info("draw function is invalid for ocr_rec!")
  42. return None
  43. elif "text" not in keys: # for ocr_det
  44. logger.info("draw text boxes only!")
  45. boxes = []
  46. for dno in range(len(res)):
  47. boxes.append(res[dno]["text_region"])
  48. boxes = np.array(boxes)
  49. draw_img = draw_boxes(image, boxes)
  50. return draw_img
  51. else: # for ocr_system
  52. logger.info("draw boxes and texts!")
  53. boxes = []
  54. texts = []
  55. scores = []
  56. for dno in range(len(res)):
  57. boxes.append(res[dno]["text_region"])
  58. texts.append(res[dno]["text"])
  59. scores.append(res[dno]["confidence"])
  60. boxes = np.array(boxes)
  61. scores = np.array(scores)
  62. draw_img = draw_ocr(image, boxes, texts, scores, draw_txt=True, drop_score=0.5)
  63. return draw_img
  64. def save_structure_res(res, save_folder, image_file):
  65. img = cv2.imread(image_file)
  66. excel_save_folder = os.path.join(save_folder, os.path.basename(image_file))
  67. os.makedirs(excel_save_folder, exist_ok=True)
  68. # save res
  69. with open(os.path.join(excel_save_folder, "res.txt"), "w", encoding="utf8") as f:
  70. for region in res:
  71. if region["type"] == "Table":
  72. excel_path = os.path.join(
  73. excel_save_folder, "{}.xlsx".format(region["bbox"])
  74. )
  75. to_excel(region["res"], excel_path)
  76. elif region["type"] == "Figure":
  77. x1, y1, x2, y2 = region["bbox"]
  78. print(region["bbox"])
  79. roi_img = img[y1:y2, x1:x2, :]
  80. img_path = os.path.join(
  81. excel_save_folder, "{}.jpg".format(region["bbox"])
  82. )
  83. cv2.imwrite(img_path, roi_img)
  84. else:
  85. for text_result in region["res"]:
  86. f.write("{}\n".format(json.dumps(text_result)))
  87. def main(args):
  88. image_file_list = get_image_file_list(args.image_dir)
  89. is_visualize = False
  90. headers = {"Content-type": "application/json"}
  91. cnt = 0
  92. total_time = 0
  93. for image_file in image_file_list:
  94. img = open(image_file, "rb").read()
  95. if img is None:
  96. logger.info("error in loading image:{}".format(image_file))
  97. continue
  98. img_name = os.path.basename(image_file)
  99. # seed http request
  100. starttime = time.time()
  101. data = {"images": [cv2_to_base64(img)]}
  102. r = requests.post(url=args.server_url, headers=headers, data=json.dumps(data))
  103. elapse = time.time() - starttime
  104. total_time += elapse
  105. logger.info("Predict time of %s: %.3fs" % (image_file, elapse))
  106. res = r.json()["results"][0]
  107. logger.info(res)
  108. if args.visualize:
  109. draw_img = None
  110. if "structure_table" in args.server_url:
  111. to_excel(res["html"], "./{}.xlsx".format(img_name))
  112. elif "structure_system" in args.server_url:
  113. save_structure_res(res["regions"], args.output, image_file)
  114. else:
  115. draw_img = draw_server_result(image_file, res)
  116. if draw_img is not None:
  117. if not os.path.exists(args.output):
  118. os.makedirs(args.output)
  119. cv2.imwrite(
  120. os.path.join(args.output, os.path.basename(image_file)),
  121. draw_img[:, :, ::-1],
  122. )
  123. logger.info(
  124. "The visualized image saved in {}".format(
  125. os.path.join(args.output, os.path.basename(image_file))
  126. )
  127. )
  128. cnt += 1
  129. if cnt % 100 == 0:
  130. logger.info("{} processed".format(cnt))
  131. logger.info("avg time cost: {}".format(float(total_time) / cnt))
  132. def parse_args():
  133. import argparse
  134. parser = argparse.ArgumentParser(description="args for hub serving")
  135. parser.add_argument("--server_url", type=str, required=True)
  136. parser.add_argument("--image_dir", type=str, required=True)
  137. parser.add_argument("--visualize", type=str2bool, default=False)
  138. parser.add_argument("--output", type=str, default="./hubserving_result")
  139. args = parser.parse_args()
  140. return args
  141. if __name__ == "__main__":
  142. args = parse_args()
  143. main(args)