predict_system.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. import subprocess
  17. __dir__ = os.path.dirname(os.path.abspath(__file__))
  18. sys.path.append(__dir__)
  19. sys.path.insert(0, os.path.abspath(os.path.join(__dir__, "../")))
  20. os.environ["FLAGS_allocator_strategy"] = "auto_growth"
  21. import cv2
  22. import json
  23. import numpy as np
  24. import time
  25. import logging
  26. from copy import deepcopy
  27. from paddle.utils import try_import
  28. from ppocr.utils.utility import get_image_file_list, check_and_read
  29. from ppocr.utils.logging import get_logger
  30. from ppocr.utils.visual import draw_ser_results, draw_re_results
  31. from tools.infer.predict_system import TextSystem
  32. from tools.infer.predict_rec import TextRecognizer
  33. from ppstructure.layout.predict_layout import LayoutPredictor
  34. from ppstructure.table.predict_table import TableSystem, to_excel
  35. from ppstructure.utility import parse_args, draw_structure_result, cal_ocr_word_box
  36. logger = get_logger()
  37. class StructureSystem(object):
  38. def __init__(self, args):
  39. self.mode = args.mode
  40. self.recovery = args.recovery
  41. self.image_orientation_predictor = None
  42. if args.image_orientation:
  43. import paddleclas
  44. self.image_orientation_predictor = paddleclas.PaddleClas(
  45. model_name="text_image_orientation"
  46. )
  47. if self.mode == "structure":
  48. if not args.show_log:
  49. logger.setLevel(logging.INFO)
  50. if args.layout == False and args.ocr == True:
  51. args.ocr = False
  52. logger.warning(
  53. "When args.layout is false, args.ocr is automatically set to false"
  54. )
  55. # init model
  56. self.layout_predictor = None
  57. self.text_system = None
  58. self.table_system = None
  59. self.formula_system = None
  60. if args.layout:
  61. self.layout_predictor = LayoutPredictor(args)
  62. if args.ocr:
  63. self.text_system = TextSystem(args)
  64. if args.table:
  65. if self.text_system is not None:
  66. self.table_system = TableSystem(
  67. args,
  68. self.text_system.text_detector,
  69. self.text_system.text_recognizer,
  70. )
  71. else:
  72. self.table_system = TableSystem(args)
  73. if args.formula:
  74. args_formula = deepcopy(args)
  75. args_formula.rec_algorithm = args.formula_algorithm
  76. args_formula.rec_model_dir = args.formula_model_dir
  77. args_formula.rec_char_dict_path = args.formula_char_dict_path
  78. args_formula.rec_batch_num = args.formula_batch_num
  79. self.formula_system = TextRecognizer(args_formula)
  80. elif self.mode == "kie":
  81. from ppstructure.kie.predict_kie_token_ser_re import SerRePredictor
  82. self.kie_predictor = SerRePredictor(args)
  83. self.return_word_box = args.return_word_box
  84. def __call__(self, img, return_ocr_result_in_table=False, img_idx=0):
  85. time_dict = {
  86. "image_orientation": 0,
  87. "layout": 0,
  88. "table": 0,
  89. "table_match": 0,
  90. "formula": 0,
  91. "det": 0,
  92. "rec": 0,
  93. "kie": 0,
  94. "all": 0,
  95. }
  96. start = time.time()
  97. if self.image_orientation_predictor is not None:
  98. tic = time.time()
  99. cls_result = self.image_orientation_predictor.predict(input_data=img)
  100. cls_res = next(cls_result)
  101. angle = cls_res[0]["label_names"][0]
  102. cv_rotate_code = {
  103. "90": cv2.ROTATE_90_COUNTERCLOCKWISE,
  104. "180": cv2.ROTATE_180,
  105. "270": cv2.ROTATE_90_CLOCKWISE,
  106. }
  107. if angle in cv_rotate_code:
  108. img = cv2.rotate(img, cv_rotate_code[angle])
  109. toc = time.time()
  110. time_dict["image_orientation"] = toc - tic
  111. if self.mode == "structure":
  112. ori_im = img.copy()
  113. if self.layout_predictor is not None:
  114. layout_res, elapse = self.layout_predictor(img)
  115. time_dict["layout"] += elapse
  116. else:
  117. h, w = ori_im.shape[:2]
  118. layout_res = [dict(bbox=None, label="table", score=0.0)]
  119. # As reported in issues such as #10270 and #11665, the old
  120. # implementation, which recognizes texts from the layout regions,
  121. # has problems with OCR recognition accuracy.
  122. #
  123. # To enhance the OCR recognition accuracy, we implement a patch fix
  124. # that first use text_system to detect and recognize all text information
  125. # and then filter out relevant texts according to the layout regions.
  126. text_res = None
  127. if self.text_system is not None:
  128. text_res, ocr_time_dict = self._predict_text(img)
  129. time_dict["det"] += ocr_time_dict["det"]
  130. time_dict["rec"] += ocr_time_dict["rec"]
  131. res_list = []
  132. for region in layout_res:
  133. res = ""
  134. if region["bbox"] is not None:
  135. x1, y1, x2, y2 = region["bbox"]
  136. x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
  137. roi_img = ori_im[y1:y2, x1:x2, :]
  138. else:
  139. x1, y1, x2, y2 = 0, 0, w, h
  140. roi_img = ori_im
  141. bbox = [x1, y1, x2, y2]
  142. if region["label"] == "table":
  143. if self.table_system is not None:
  144. res, table_time_dict = self.table_system(
  145. roi_img, return_ocr_result_in_table
  146. )
  147. time_dict["table"] += table_time_dict["table"]
  148. time_dict["table_match"] += table_time_dict["match"]
  149. time_dict["det"] += table_time_dict["det"]
  150. time_dict["rec"] += table_time_dict["rec"]
  151. elif region["label"] == "equation" and self.formula_system is not None:
  152. latex_res, formula_time = self.formula_system([roi_img])
  153. time_dict["formula"] += formula_time
  154. res = {"latex": latex_res[0]}
  155. else:
  156. if text_res is not None:
  157. # Filter the text results whose regions intersect with the current layout bbox.
  158. res = self._filter_text_res(text_res, bbox)
  159. res_list.append(
  160. {
  161. "type": region["label"].lower(),
  162. "bbox": bbox,
  163. "img": roi_img,
  164. "res": res,
  165. "img_idx": img_idx,
  166. "score": region["score"],
  167. }
  168. )
  169. end = time.time()
  170. time_dict["all"] = end - start
  171. return res_list, time_dict
  172. elif self.mode == "kie":
  173. re_res, elapse = self.kie_predictor(img)
  174. time_dict["kie"] = elapse
  175. time_dict["all"] = elapse
  176. return re_res[0], time_dict
  177. return None, None
  178. def _predict_text(self, img):
  179. filter_boxes, filter_rec_res, ocr_time_dict = self.text_system(img)
  180. # remove style char,
  181. # when using the recognition model trained on the PubtabNet dataset,
  182. # it will recognize the text format in the table, such as <b>
  183. style_token = [
  184. "<strike>",
  185. "<strike>",
  186. "<sup>",
  187. "</sub>",
  188. "<b>",
  189. "</b>",
  190. "<sub>",
  191. "</sup>",
  192. "<overline>",
  193. "</overline>",
  194. "<underline>",
  195. "</underline>",
  196. "<i>",
  197. "</i>",
  198. ]
  199. res = []
  200. for box, rec_res in zip(filter_boxes, filter_rec_res):
  201. rec_str, rec_conf = rec_res[0], rec_res[1]
  202. for token in style_token:
  203. if token in rec_str:
  204. rec_str = rec_str.replace(token, "")
  205. if self.return_word_box:
  206. word_box_content_list, word_box_list = cal_ocr_word_box(
  207. rec_str, box, rec_res[2]
  208. )
  209. res.append(
  210. {
  211. "text": rec_str,
  212. "confidence": float(rec_conf),
  213. "text_region": box.tolist(),
  214. "text_word": word_box_content_list,
  215. "text_word_region": word_box_list,
  216. }
  217. )
  218. else:
  219. res.append(
  220. {
  221. "text": rec_str,
  222. "confidence": float(rec_conf),
  223. "text_region": box.tolist(),
  224. }
  225. )
  226. return res, ocr_time_dict
  227. def _filter_text_res(self, text_res, bbox):
  228. res = []
  229. for r in text_res:
  230. box = r["text_region"]
  231. rect = box[0][0], box[0][1], box[2][0], box[2][1]
  232. if self._has_intersection(bbox, rect):
  233. res.append(r)
  234. return res
  235. def _has_intersection(self, rect1, rect2):
  236. x_min1, y_min1, x_max1, y_max1 = rect1
  237. x_min2, y_min2, x_max2, y_max2 = rect2
  238. if x_min1 > x_max2 or x_max1 < x_min2:
  239. return False
  240. if y_min1 > y_max2 or y_max1 < y_min2:
  241. return False
  242. return True
  243. def save_structure_res(res, save_folder, img_name, img_idx=0):
  244. excel_save_folder = os.path.join(save_folder, img_name)
  245. os.makedirs(excel_save_folder, exist_ok=True)
  246. res_cp = deepcopy(res)
  247. # save res
  248. with open(
  249. os.path.join(excel_save_folder, "res_{}.txt".format(img_idx)),
  250. "w",
  251. encoding="utf8",
  252. ) as f:
  253. for region in res_cp:
  254. roi_img = region.pop("img")
  255. f.write("{}\n".format(json.dumps(region)))
  256. if (
  257. region["type"].lower() == "table"
  258. and len(region["res"]) > 0
  259. and "html" in region["res"]
  260. ):
  261. excel_path = os.path.join(
  262. excel_save_folder, "{}_{}.xlsx".format(region["bbox"], img_idx)
  263. )
  264. to_excel(region["res"]["html"], excel_path)
  265. elif region["type"].lower() == "figure":
  266. img_path = os.path.join(
  267. excel_save_folder, "{}_{}.jpg".format(region["bbox"], img_idx)
  268. )
  269. cv2.imwrite(img_path, roi_img)
  270. def main(args):
  271. image_file_list = get_image_file_list(args.image_dir)
  272. image_file_list = image_file_list
  273. image_file_list = image_file_list[args.process_id :: args.total_process_num]
  274. if not args.use_pdf2docx_api:
  275. structure_sys = StructureSystem(args)
  276. save_folder = os.path.join(args.output, structure_sys.mode)
  277. os.makedirs(save_folder, exist_ok=True)
  278. img_num = len(image_file_list)
  279. for i, image_file in enumerate(image_file_list):
  280. logger.info("[{}/{}] {}".format(i, img_num, image_file))
  281. img, flag_gif, flag_pdf = check_and_read(image_file)
  282. img_name = os.path.basename(image_file).split(".")[0]
  283. if args.recovery and args.use_pdf2docx_api and flag_pdf:
  284. try_import("pdf2docx")
  285. from pdf2docx.converter import Converter
  286. os.makedirs(args.output, exist_ok=True)
  287. docx_file = os.path.join(args.output, "{}_api.docx".format(img_name))
  288. cv = Converter(image_file)
  289. cv.convert(docx_file)
  290. cv.close()
  291. logger.info("docx save to {}".format(docx_file))
  292. continue
  293. if not flag_gif and not flag_pdf:
  294. img = cv2.imread(image_file)
  295. if not flag_pdf:
  296. if img is None:
  297. logger.error("error in loading image:{}".format(image_file))
  298. continue
  299. imgs = [img]
  300. else:
  301. imgs = img
  302. all_res = []
  303. for index, img in enumerate(imgs):
  304. res, time_dict = structure_sys(img, img_idx=index)
  305. img_save_path = os.path.join(
  306. save_folder, img_name, "show_{}.jpg".format(index)
  307. )
  308. os.makedirs(os.path.join(save_folder, img_name), exist_ok=True)
  309. if structure_sys.mode == "structure" and res != []:
  310. draw_img = draw_structure_result(img, res, args.vis_font_path)
  311. save_structure_res(res, save_folder, img_name, index)
  312. elif structure_sys.mode == "kie":
  313. if structure_sys.kie_predictor.predictor is not None:
  314. draw_img = draw_re_results(img, res, font_path=args.vis_font_path)
  315. else:
  316. draw_img = draw_ser_results(img, res, font_path=args.vis_font_path)
  317. with open(
  318. os.path.join(save_folder, img_name, "res_{}_kie.txt".format(index)),
  319. "w",
  320. encoding="utf8",
  321. ) as f:
  322. res_str = "{}\t{}\n".format(
  323. image_file, json.dumps({"ocr_info": res}, ensure_ascii=False)
  324. )
  325. f.write(res_str)
  326. if res != []:
  327. cv2.imwrite(img_save_path, draw_img)
  328. logger.info("result save to {}".format(img_save_path))
  329. if args.recovery and res != []:
  330. from ppstructure.recovery.recovery_to_doc import (
  331. sorted_layout_boxes,
  332. convert_info_docx,
  333. )
  334. from ppstructure.recovery.recovery_to_markdown import (
  335. convert_info_markdown,
  336. )
  337. h, w, _ = img.shape
  338. res = sorted_layout_boxes(res, w)
  339. all_res += res
  340. if args.recovery and all_res != []:
  341. try:
  342. convert_info_docx(img, all_res, save_folder, img_name)
  343. if args.recovery_to_markdown:
  344. convert_info_markdown(all_res, save_folder, img_name)
  345. except Exception as ex:
  346. logger.error(
  347. "error in layout recovery image:{}, err msg: {}".format(
  348. image_file, ex
  349. )
  350. )
  351. continue
  352. logger.info("Predict time : {:.3f}s".format(time_dict["all"]))
  353. if __name__ == "__main__":
  354. args = parse_args()
  355. if args.use_mp:
  356. p_list = []
  357. total_process_num = args.total_process_num
  358. for process_id in range(total_process_num):
  359. cmd = (
  360. [sys.executable, "-u"]
  361. + sys.argv
  362. + ["--process_id={}".format(process_id), "--use_mp={}".format(False)]
  363. )
  364. p = subprocess.Popen(cmd, stdout=sys.stdout, stderr=sys.stdout)
  365. p_list.append(p)
  366. for p in p_list:
  367. p.wait()
  368. else:
  369. main(args)