convert_image.py 12 KB

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