convert_image.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. # encoding=utf8
  2. import inspect
  3. import io
  4. import logging
  5. import os
  6. import sys
  7. import time
  8. import requests
  9. import numpy as np
  10. from ocr.paddleocr import PaddleOCR
  11. sys.path.append(os.path.dirname(__file__) + "/../")
  12. from pdfminer.layout import LTLine
  13. import traceback
  14. import cv2
  15. from format_convert import get_memory_info, _global
  16. from format_convert.utils import judge_error_code, add_div, LineTable, get_table_html, get_logger, log, memory_decorator
  17. from format_convert.table_correct import get_rotated_image
  18. from format_convert.convert_need_interface import from_otr_interface, from_ocr_interface, from_gpu_interface_redis
  19. from otr.table_line import table_preprocess, table_postprocess
  20. def image_process(image_np, image_path, is_from_pdf=False, is_from_docx=False, use_ocr=True):
  21. from format_convert.convert_tree import _Table, _Sentence
  22. def get_cluster(t_list, b_list, axis):
  23. zip_list = list(zip(t_list, b_list))
  24. if len(zip_list) == 0:
  25. return t_list, b_list
  26. if len(zip_list[0]) > 0:
  27. zip_list.sort(key=lambda x: x[1][axis][1])
  28. cluster_list = []
  29. margin = 5
  30. for text, bbox in zip_list:
  31. _find = 0
  32. for cluster in cluster_list:
  33. if abs(cluster[1] - bbox[axis][1]) <= margin:
  34. cluster[0].append([text, bbox])
  35. cluster[1] = bbox[axis][1]
  36. _find = 1
  37. break
  38. if not _find:
  39. cluster_list.append([[[text, bbox]], bbox[axis][1]])
  40. new_text_list = []
  41. new_bbox_list = []
  42. for cluster in cluster_list:
  43. # print("=============convert_image")
  44. # print("cluster_list", cluster)
  45. center_y = 0
  46. for text, bbox in cluster[0]:
  47. center_y += bbox[axis][1]
  48. center_y = int(center_y / len(cluster[0]))
  49. for text, bbox in cluster[0]:
  50. bbox[axis][1] = center_y
  51. new_text_list.append(text)
  52. new_bbox_list.append(bbox)
  53. # print("cluster_list", cluster)
  54. return new_text_list, new_bbox_list
  55. def merge_textbox(textbox_list, in_objs):
  56. delete_obj = []
  57. threshold = 5
  58. for k in range(len(textbox_list)):
  59. tb1 = textbox_list[k]
  60. if tb1 not in in_objs and tb1 not in delete_obj:
  61. for m in range(k+1, len(textbox_list)):
  62. tb2 = textbox_list[m]
  63. if abs(tb1.bbox[1]-tb2.bbox[1]) <= threshold \
  64. and abs(tb1.bbox[3]-tb2.bbox[3]) <= threshold:
  65. if tb1.bbox[0] <= tb2.bbox[0]:
  66. tb1.text = tb1.text + tb2.text
  67. else:
  68. tb1.text = tb2.text + tb1.text
  69. tb1.bbox[0] = min(tb1.bbox[0], tb2.bbox[0])
  70. tb1.bbox[2] = max(tb1.bbox[2], tb2.bbox[2])
  71. delete_obj.append(tb2)
  72. for _obj in delete_obj:
  73. if _obj in textbox_list:
  74. textbox_list.remove(_obj)
  75. return textbox_list
  76. log("into image_preprocess")
  77. try:
  78. # 图片倾斜校正,写入原来的图片路径
  79. # print("image_process", image_path)
  80. g_r_i = get_rotated_image(image_np, image_path)
  81. if judge_error_code(g_r_i):
  82. if is_from_docx:
  83. return []
  84. else:
  85. return g_r_i
  86. image_np = cv2.imread(image_path)
  87. if image_np is None:
  88. return []
  89. # otr需要图片resize成模型所需大小, 写入另一个路径
  90. best_h, best_w = get_best_predict_size(image_np)
  91. image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  92. image_resize_path = image_path.split(".")[0] + "_resize_otr." + image_path.split(".")[-1]
  93. cv2.imwrite(image_resize_path, image_resize)
  94. # 调用otr模型接口
  95. with open(image_resize_path, "rb") as f:
  96. image_bytes = f.read()
  97. list_line = from_otr_interface(image_bytes, is_from_pdf)
  98. if judge_error_code(list_line):
  99. return list_line
  100. # # 预处理
  101. # if is_from_pdf:
  102. # prob = 0.2
  103. # else:
  104. # prob = 0.5
  105. # with open(image_resize_path, "rb") as f:
  106. # image_bytes = f.read()
  107. # img_new, inputs = table_preprocess(image_bytes, prob)
  108. # if type(img_new) is list and judge_error_code(img_new):
  109. # return img_new
  110. # log("img_new.shape " + str(img_new.shape))
  111. #
  112. # # 调用模型运行接口
  113. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  114. # result = from_gpu_interface(_dict, model_type="otr", predictor_type="")
  115. # if judge_error_code(result):
  116. # logging.error("from_gpu_interface failed! " + str(result))
  117. # raise requests.exceptions.RequestException
  118. #
  119. # pred = result.get("preds")
  120. # gpu_time = result.get("gpu_time")
  121. # log("otr model predict time " + str(gpu_time))
  122. #
  123. # # # 解压numpy
  124. # # decompressed_array = io.BytesIO()
  125. # # decompressed_array.write(pred)
  126. # # decompressed_array.seek(0)
  127. # # pred = np.load(decompressed_array, allow_pickle=True)['arr_0']
  128. # # log("inputs.shape" + str(pred.shape))
  129. #
  130. # # 后处理
  131. # list_line = table_postprocess(img_new, pred, prob)
  132. # log("len(list_line) " + str(len(list_line)))
  133. # if judge_error_code(list_line):
  134. # return list_line
  135. # otr resize后得到的bbox根据比例还原
  136. start_time = time.time()
  137. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  138. for i in range(len(list_line)):
  139. point = list_line[i]
  140. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  141. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  142. log("otr resize bbox recover " + str(time.time()-start_time))
  143. # ocr图片过大内存溢出,需resize
  144. start_time = time.time()
  145. threshold = 3000
  146. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  147. best_h, best_w = get_best_predict_size2(image_np, threshold)
  148. image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  149. # image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  150. # cv2.imwrite(image_resize_path, image_resize)
  151. log("ocr resize before " + str(time.time()-start_time))
  152. # 调用ocr模型接口
  153. with open(image_resize_path, "rb") as f:
  154. image_bytes = f.read()
  155. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  156. if judge_error_code(text_list):
  157. return text_list
  158. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  159. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  160. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  161. # # 循环每张图片识别结果
  162. # text_list = []
  163. # bbox_list = []
  164. # for line in results:
  165. # # print("ocr_interface line", line)
  166. # text_list.append(line[-1][0])
  167. # bbox_list.append(line[0])
  168. # if len(text_list) == 0:
  169. # return []
  170. # ocr resize后的bbox还原
  171. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  172. for i in range(len(bbox_list)):
  173. point = bbox_list[i]
  174. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  175. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  176. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  177. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  178. # 对文字框的y进行聚类
  179. text_list, bbox_list = get_cluster(text_list, bbox_list, 0)
  180. text_list, bbox_list = get_cluster(text_list, bbox_list, 2)
  181. # 调用现成方法形成表格
  182. try:
  183. from format_convert.convert_tree import TableLine
  184. list_lines = []
  185. for line in list_line:
  186. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  187. from format_convert.convert_tree import TextBox
  188. list_text_boxes = []
  189. for i in range(len(bbox_list)):
  190. bbox = bbox_list[i]
  191. b_text = text_list[i]
  192. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  193. bbox[2][0], bbox[2][1]], b_text))
  194. lt = LineTable()
  195. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  196. # 合并同一行textbox
  197. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  198. obj_list = []
  199. for table in tables:
  200. obj_list.append(_Table(table["table"], table["bbox"]))
  201. for text_box in list_text_boxes:
  202. if text_box not in obj_in_table:
  203. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  204. return obj_list
  205. except:
  206. traceback.print_exc()
  207. return [-8]
  208. except Exception as e:
  209. log("image_preprocess error")
  210. traceback.print_exc()
  211. return [-1]
  212. @memory_decorator
  213. def picture2text(path, html=False):
  214. log("into picture2text")
  215. try:
  216. # 判断图片中表格
  217. img = cv2.imread(path)
  218. if img is None:
  219. return [-3]
  220. text = image_process(img, path)
  221. if judge_error_code(text):
  222. return text
  223. if html:
  224. text = add_div(text)
  225. return [text]
  226. except Exception as e:
  227. log("picture2text error!")
  228. print("picture2text", traceback.print_exc())
  229. return [-1]
  230. def get_best_predict_size(image_np, times=64):
  231. sizes = []
  232. for i in range(1, 100):
  233. if i*times <= 1300:
  234. sizes.append(i*times)
  235. sizes.sort(key=lambda x: x, reverse=True)
  236. min_len = 10000
  237. best_height = sizes[0]
  238. for height in sizes:
  239. if abs(image_np.shape[0] - height) < min_len:
  240. min_len = abs(image_np.shape[0] - height)
  241. best_height = height
  242. min_len = 10000
  243. best_width = sizes[0]
  244. for width in sizes:
  245. if abs(image_np.shape[1] - width) < min_len:
  246. min_len = abs(image_np.shape[1] - width)
  247. best_width = width
  248. return best_height, best_width
  249. def get_best_predict_size2(image_np, threshold=3000):
  250. h, w = image_np.shape[:2]
  251. scale = threshold / max(h, w)
  252. h = int(h * scale)
  253. w = int(w * scale)
  254. return h, w
  255. class ImageConvert:
  256. def __init__(self, path, unique_type_dir):
  257. from format_convert.convert_tree import _Document
  258. self._doc = _Document(path)
  259. self.path = path
  260. self.unique_type_dir = unique_type_dir
  261. def init_package(self):
  262. # 各个包初始化
  263. try:
  264. with open(self.path, "rb") as f:
  265. self.image = f.read()
  266. except:
  267. log("cannot open image!")
  268. traceback.print_exc()
  269. self._doc.error_code = [-3]
  270. def convert(self):
  271. from format_convert.convert_tree import _Page, _Image
  272. self.init_package()
  273. if self._doc.error_code is not None:
  274. return
  275. _page = _Page(None, 0)
  276. _image = _Image(self.image, self.path)
  277. _page.add_child(_image)
  278. self._doc.add_child(_page)
  279. def get_html(self):
  280. try:
  281. self.convert()
  282. except:
  283. traceback.print_exc()
  284. self._doc.error_code = [-1]
  285. if self._doc.error_code is not None:
  286. return self._doc.error_code
  287. return self._doc.get_html()