convert_image.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. # 调用gpu共享内存处理
  131. # _dict = {"inputs": inputs, "md5": _global.get("md5")}
  132. # result = from_gpu_share_memory(_dict, model_type="otr", predictor_type="")
  133. # if judge_error_code(result):
  134. # logging.error("from_gpu_interface failed! " + str(result))
  135. # raise requests.exceptions.RequestException
  136. #
  137. # pred = result.get("preds")
  138. # gpu_time = result.get("gpu_time")
  139. # log("otr model predict time " + str(gpu_time))
  140. #
  141. # # 后处理
  142. # list_line = table_postprocess(img_new, pred, prob)
  143. # log("len(list_line) " + str(len(list_line)))
  144. # if judge_error_code(list_line):
  145. # return list_line
  146. # otr resize后得到的bbox根据比例还原
  147. start_time = time.time()
  148. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  149. for i in range(len(list_line)):
  150. point = list_line[i]
  151. list_line[i] = [int(point[0]*ratio[1]), int(point[1]*ratio[0]),
  152. int(point[2]*ratio[1]), int(point[3]*ratio[0])]
  153. log("otr resize bbox recover " + str(time.time()-start_time))
  154. # ocr图片过大内存溢出,需resize
  155. start_time = time.time()
  156. threshold = 3000
  157. if image_np.shape[0] >= threshold or image_np.shape[1] >= threshold:
  158. best_h, best_w = get_best_predict_size2(image_np, threshold)
  159. image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  160. image_resize_path = image_path.split(".")[0] + "_resize_ocr." + image_path.split(".")[-1]
  161. cv2.imwrite(image_resize_path, image_resize)
  162. log("ocr resize before " + str(time.time()-start_time))
  163. # 调用ocr模型接口
  164. with open(image_resize_path, "rb") as f:
  165. image_bytes = f.read()
  166. text_list, bbox_list = from_ocr_interface(image_bytes, is_table=True)
  167. if judge_error_code(text_list):
  168. return text_list
  169. # # PaddleOCR内部包括预处理,调用模型运行接口,后处理
  170. # paddle_ocr = PaddleOCR(use_angle_cls=True, lang="ch")
  171. # results = paddle_ocr.ocr(image_resize, det=True, rec=True, cls=True)
  172. # # 循环每张图片识别结果
  173. # text_list = []
  174. # bbox_list = []
  175. # for line in results:
  176. # # print("ocr_interface line", line)
  177. # text_list.append(line[-1][0])
  178. # bbox_list.append(line[0])
  179. # if len(text_list) == 0:
  180. # return []
  181. # ocr resize后的bbox还原
  182. ratio = (image_np.shape[0]/best_h, image_np.shape[1]/best_w)
  183. for i in range(len(bbox_list)):
  184. point = bbox_list[i]
  185. bbox_list[i] = [[int(point[0][0]*ratio[1]), int(point[0][1]*ratio[0])],
  186. [int(point[1][0]*ratio[1]), int(point[1][1]*ratio[0])],
  187. [int(point[2][0]*ratio[1]), int(point[2][1]*ratio[0])],
  188. [int(point[3][0]*ratio[1]), int(point[3][1]*ratio[0])]]
  189. # for _a,_b in zip(text_list,bbox_list):
  190. # print("bbox1",_a,_b)
  191. # 调用现成方法形成表格
  192. try:
  193. from format_convert.convert_tree import TableLine
  194. list_lines = []
  195. for line in list_line:
  196. list_lines.append(LTLine(1, (line[0], line[1]), (line[2], line[3])))
  197. from format_convert.convert_tree import TextBox
  198. list_text_boxes = []
  199. for i in range(len(bbox_list)):
  200. bbox = bbox_list[i]
  201. b_text = text_list[i]
  202. list_text_boxes.append(TextBox([bbox[0][0], bbox[0][1],
  203. bbox[2][0], bbox[2][1]], b_text))
  204. lt = LineTable()
  205. tables, obj_in_table, _ = lt.recognize_table(list_text_boxes, list_lines, False)
  206. # 合并同一行textbox
  207. list_text_boxes = merge_textbox(list_text_boxes, obj_in_table)
  208. obj_list = []
  209. for table in tables:
  210. obj_list.append(_Table(table["table"], table["bbox"]))
  211. for text_box in list_text_boxes:
  212. if text_box not in obj_in_table:
  213. obj_list.append(_Sentence(text_box.get_text(), text_box.bbox))
  214. return obj_list
  215. except:
  216. traceback.print_exc()
  217. return [-8]
  218. except Exception as e:
  219. log("image_preprocess error")
  220. traceback.print_exc()
  221. return [-1]
  222. @memory_decorator
  223. def picture2text(path, html=False):
  224. log("into picture2text")
  225. try:
  226. # 判断图片中表格
  227. img = cv2.imread(path)
  228. if img is None:
  229. return [-3]
  230. text = image_process(img, path)
  231. if judge_error_code(text):
  232. return text
  233. if html:
  234. text = add_div(text)
  235. return [text]
  236. except Exception as e:
  237. log("picture2text error!")
  238. print("picture2text", traceback.print_exc())
  239. return [-1]
  240. def get_best_predict_size(image_np, times=64):
  241. sizes = []
  242. for i in range(1, 100):
  243. if i*times <= 1300:
  244. sizes.append(i*times)
  245. sizes.sort(key=lambda x: x, reverse=True)
  246. min_len = 10000
  247. best_height = sizes[0]
  248. for height in sizes:
  249. if abs(image_np.shape[0] - height) < min_len:
  250. min_len = abs(image_np.shape[0] - height)
  251. best_height = height
  252. min_len = 10000
  253. best_width = sizes[0]
  254. for width in sizes:
  255. if abs(image_np.shape[1] - width) < min_len:
  256. min_len = abs(image_np.shape[1] - width)
  257. best_width = width
  258. return best_height, best_width
  259. def get_best_predict_size2(image_np, threshold=3000):
  260. h, w = image_np.shape[:2]
  261. scale = threshold / max(h, w)
  262. h = int(h * scale)
  263. w = int(w * scale)
  264. return h, w
  265. class ImageConvert:
  266. def __init__(self, path, unique_type_dir):
  267. from format_convert.convert_tree import _Document
  268. self._doc = _Document(path)
  269. self.path = path
  270. self.unique_type_dir = unique_type_dir
  271. def init_package(self):
  272. # 各个包初始化
  273. try:
  274. with open(self.path, "rb") as f:
  275. self.image = f.read()
  276. except:
  277. log("cannot open image!")
  278. traceback.print_exc()
  279. self._doc.error_code = [-3]
  280. def convert(self):
  281. from format_convert.convert_tree import _Page, _Image
  282. self.init_package()
  283. if self._doc.error_code is not None:
  284. return
  285. _page = _Page(None, 0)
  286. _image = _Image(self.image, self.path)
  287. _page.add_child(_image)
  288. self._doc.add_child(_page)
  289. def get_html(self):
  290. try:
  291. self.convert()
  292. except:
  293. traceback.print_exc()
  294. self._doc.error_code = [-1]
  295. if self._doc.error_code is not None:
  296. return self._doc.error_code
  297. return self._doc.get_html()