otr_interface.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. import base64
  2. import json
  3. import multiprocessing as mp
  4. import os
  5. import sys
  6. import traceback
  7. # os.environ['TF_XLA_FLAGS'] = '--tf_xla_cpu_global_jit'
  8. # os.environ['CUDA_VISIBLE_DEVICES'] = "0"
  9. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  10. from format_convert.max_compute_config import max_compute
  11. import tensorflow as tf
  12. MAX_COMPUTE = max_compute
  13. if not MAX_COMPUTE:
  14. # tensorflow 内存设置
  15. try:
  16. gpus = tf.config.list_physical_devices('GPU')
  17. if len(gpus) > 0:
  18. tf.config.experimental.set_virtual_device_configuration(
  19. gpus[0],
  20. [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=2048)])
  21. except:
  22. traceback.print_exc()
  23. # pass
  24. # gpus = tf.config.list_physical_devices('GPU')
  25. # for gpu in gpus: # 如果使用多块GPU时
  26. # tf.config.experimental.set_memory_growth(gpu, True)
  27. os.environ['CUDA_CACHE_MAXSIZE'] = str(2147483648)
  28. os.environ['CUDA_CACHE_DISABLE'] = str(0)
  29. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.6)
  30. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
  31. import time
  32. import logging
  33. import cv2
  34. import numpy as np
  35. from flask import Flask, request
  36. from format_convert.utils import request_post, judge_error_code, get_intranet_ip, log, get_md5_from_bytes, get_platform
  37. from otr.table_line import get_points, get_split_line, get_points_row, \
  38. get_points_col, \
  39. delete_close_points, fix_outline, get_bbox, get_outline_point, delete_contain_bbox, points_to_line, \
  40. fix_inner, merge_line, fix_corner, delete_outline, table_net
  41. from otr.table_line_new import table_line
  42. from format_convert import _global
  43. # 接口配置
  44. app = Flask(__name__)
  45. @app.route('/otr', methods=['POST'])
  46. def _otr():
  47. _global._init()
  48. _global.update({"port": globals().get("port")})
  49. start_time = time.time()
  50. log("into otr_interface _otr")
  51. try:
  52. if not request.form:
  53. log("otr no data!")
  54. return json.dumps({"list_line": str([-9])})
  55. otr_model = globals().get("global_otr_model")
  56. if otr_model is None:
  57. otr_model = OtrModels().get_model()
  58. globals().update({"global_otr_model": otr_model})
  59. data = request.form.get("data")
  60. is_from_pdf = request.form.get("is_from_pdf")
  61. _md5 = request.form.get("md5")
  62. _global.update({"md5": _md5})
  63. list_lines = otr(data, otr_model, is_from_pdf)
  64. return json.dumps(list_lines)
  65. except TimeoutError:
  66. return json.dumps({"list_line": str([-5])})
  67. except:
  68. traceback.print_exc()
  69. return json.dumps({"list_line": str([-1])})
  70. finally:
  71. log("otr interface finish time " + str(time.time()-start_time))
  72. def otr(data, otr_model, is_from_pdf):
  73. log("into otr_interface otr")
  74. log('otr is_from_pdf ' + str(is_from_pdf))
  75. try:
  76. img_data = base64.b64decode(data)
  77. if is_from_pdf:
  78. list_lines = line_detect(img_data, otr_model, prob=0.2)
  79. else:
  80. list_lines = line_detect(img_data, otr_model, prob=0.5)
  81. return list_lines
  82. except TimeoutError:
  83. raise TimeoutError
  84. def table_detect2(img_data, otr_model):
  85. log("into otr_interface table_detect")
  86. start_time = time.time()
  87. try:
  88. start_time1 = time.time()
  89. # 二进制数据流转np.ndarray [np.uint8: 8位像素]
  90. img = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
  91. # log("into otr_interface table_detect 1")
  92. # cv2.imwrite("111111.jpg", img)
  93. # 将bgr转为rbg
  94. image_np = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  95. # log("into otr_interface table_detect 2")
  96. # 选择与图片最接近分辨率,以防失真
  97. # best_h, best_w = get_best_predict_size(img)
  98. print("image_np.shape", image_np.shape)
  99. best_h, best_w, _ = image_np.shape
  100. log("otr preprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  101. # 调用模型
  102. # rows, cols = table_line(image_np, otr_model)
  103. rows, cols, image_np = table_line(image_np, otr_model, size=(best_w, best_h), hprob=0.5, vprob=0.5)
  104. start_time1 = time.time()
  105. if not rows or not cols:
  106. print("points", 0, "split_lines", 0, "bboxes", 0)
  107. return {"points": str([]), "split_lines": str([]),
  108. "bboxes": str([]), "outline_points": str([]),
  109. "lines": str([])}
  110. # 查看是否正确输出rows,cols
  111. # for line in rows+cols:
  112. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  113. # (255, 0, 0), 2)
  114. # cv2.imshow("rows-cols1", img)
  115. # cv2.waitKey(0)
  116. # 处理结果
  117. # 合并错开线
  118. rows = merge_line(rows, axis=0)
  119. cols = merge_line(cols, axis=1)
  120. # 计算交点、分割线
  121. points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  122. # log("into otr_interface table_detect 5")
  123. if not points:
  124. print("points", 0, "split_lines", 0, "bboxes", 0)
  125. return {"points": str([]), "split_lines": str([]),
  126. "bboxes": str([]), "outline_points": str([]),
  127. "lines": str([])}
  128. # 清掉外围的没用的线
  129. rows, cols = delete_outline(rows, cols, points)
  130. split_lines, split_y = get_split_line(points, cols, image_np)
  131. # log("into otr_interface table_detect 6")
  132. # 计算交点所在行列,剔除相近交点
  133. row_point_list = get_points_row(points, split_y, 5)
  134. col_point_list = get_points_col(points, split_y, 5)
  135. # log("into otr_interface table_detect 7")
  136. points = delete_close_points(points, row_point_list, col_point_list)
  137. # log("into otr_interface table_detect 8")
  138. # 查看是否正确输出点
  139. # for p in points:
  140. # cv2.circle(img, (p[0], p[1]), 3, (0, 0, 255))
  141. # cv2.imshow("points", img)
  142. # cv2.waitKey(0)
  143. # 查看是否正确输出rows,cols
  144. # for line in rows+cols:
  145. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  146. # (0, 255, 0), 2)
  147. # cv2.imshow("rows-cols0", img)
  148. # cv2.waitKey(0)
  149. # 修复边框
  150. new_rows, new_cols, long_rows, long_cols = fix_outline(image_np, rows, cols, points,
  151. split_y)
  152. # print(new_cols, new_rows)
  153. if new_rows or new_cols:
  154. # 连接至补线的延长线
  155. if long_rows:
  156. rows = long_rows
  157. if long_cols:
  158. cols = long_cols
  159. # 新的补线
  160. if new_rows:
  161. rows += new_rows
  162. if new_cols:
  163. cols += new_cols
  164. # 修复边框后重新计算交点、分割线
  165. points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  166. # log("into otr_interface table_detect 10")
  167. split_lines, split_y = get_split_line(points, cols, image_np)
  168. # 计算交点所在行列,剔除相近交点
  169. row_point_list = get_points_row(points, split_y, 0)
  170. col_point_list = get_points_col(points, split_y, 0)
  171. # log("into otr_interface table_detect 11")
  172. points = delete_close_points(points, row_point_list, col_point_list)
  173. # row_point_list = get_points_row(points, split_y)
  174. # col_point_list = get_points_col(points, split_y)
  175. # log("into otr_interface table_detect 12")
  176. # 查看是否正确输出rows,cols
  177. # for line in rows+cols:
  178. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  179. # (255, 0, 0), 2)
  180. # cv2.imshow("rows-cols1", img)
  181. # cv2.waitKey(0)
  182. # 修复表格4个角
  183. rows, cols = fix_corner(rows, cols, split_y)
  184. points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  185. # row_point_list = get_points_row(points, split_y, 5)
  186. # col_point_list = get_points_col(points, split_y, 5)
  187. # print("row_point_list", row_point_list)
  188. # print("col_point_list", col_point_list)
  189. # 修复内部缺线
  190. points = fix_inner(rows, cols, points, split_y)
  191. if not points:
  192. print("points", 0, "split_lines", 0, "bboxes", 0)
  193. return {"points": str([]), "split_lines": str([]),
  194. "bboxes": str([]), "outline_points": str([]),
  195. "lines": str([])}
  196. row_point_list = get_points_row(points, split_y, 5)
  197. col_point_list = get_points_col(points, split_y, 5)
  198. # 查看是否正确输出点
  199. # for p in points:
  200. # cv2.circle(img, (p[0], p[1]), 1, (0, 255, 0), 3)
  201. # cv2.imshow("points fix", img)
  202. # cv2.waitKey(0)
  203. # 查看是否正确输出rows,cols
  204. # for line in rows+cols:
  205. # cv2.line(img, (int(line[0]), int(line[1])), (int(line[2]), int(line[3])),
  206. # (255, 0, 0), 2)
  207. # cv2.imshow("rows-cols2", img)
  208. # cv2.waitKey(0)
  209. # 根据分行分列重新得到rows、cols,避免线延长导致后续bbox生成失败
  210. # rows = points_to_line(row_point_list, axis=0)
  211. # cols = points_to_line(col_point_list, axis=1)
  212. # points = get_points(rows, cols, (image_np.shape[0], image_np.shape[1]))
  213. # row_point_list = get_points_row(points, split_y, 0)
  214. # col_point_list = get_points_col(points, split_y, 0)
  215. # 获取bbox 单元格
  216. bboxes = get_bbox(image_np, row_point_list, col_point_list, split_y, rows, cols)
  217. # log("into otr_interface table_detect 13")
  218. # 删除包含bbox
  219. if bboxes:
  220. bboxes = delete_contain_bbox(bboxes)
  221. # 查看是否能输出正确框
  222. # for box in bboxes:
  223. # cv2.rectangle(img, box[0], box[1], (0, 0, 255), 3)
  224. # cv2.imshow("bbox", img)
  225. # cv2.waitKey(0)
  226. # 补充连续框
  227. # if bboxes:
  228. # bboxes = add_continue_bbox(bboxes)
  229. #
  230. # # 删除包含bbox
  231. # bboxes = delete_contain_bbox(bboxes)
  232. # 查看是否能输出正确框
  233. # cv2.namedWindow('bbox', 0)
  234. # for box in bboxes:
  235. # cv2.rectangle(img, box[0], box[1], (0, 255, 0), 3)
  236. # cv2.imshow("bbox", img)
  237. # cv2.waitKey(0)
  238. # 查看是否正确输出点
  239. # cv2.namedWindow('points', 0)
  240. # for p in points:
  241. # cv2.circle(img, (p[0], p[1]), 3, (0, 0, 255))
  242. # cv2.imshow("points", img)
  243. # cv2.waitKey(0)
  244. # 查看是否正确输出区域分割线
  245. # cv2.namedWindow('split_lines', 0)
  246. # for line in split_lines:
  247. # cv2.line(img, line[0], line[1], (0, 0, 255), 2)
  248. # cv2.imshow("split_lines", img)
  249. # cv2.waitKey(0)
  250. # 获取每个表格的左上右下两个点
  251. outline_points = get_outline_point(points, split_y)
  252. # log("into otr_interface table_detect 14")
  253. if bboxes:
  254. print("bboxes number", len(bboxes))
  255. # print("bboxes", bboxes)
  256. else:
  257. print("bboxes number", "None")
  258. log("otr postprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  259. log("otr finish: " + str(round(float(time.time()-start_time1), 4)) + "s")
  260. return {"points": str(points), "split_lines": str(split_lines),
  261. "bboxes": str(bboxes), "outline_points": str(outline_points),
  262. "lines": str(rows+cols)}
  263. except TimeoutError:
  264. raise TimeoutError
  265. except Exception as e:
  266. log("otr_interface cannot detected table!")
  267. print("otr_interface cannot detected table!", traceback.print_exc())
  268. print("points", 0, "split_lines", 0, "bboxes", 0)
  269. log("otr postprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  270. return {"points": str([]), "split_lines": str([]), "bboxes": str([]),
  271. "outline_points": str([]), "lines": str([])}
  272. def line_detect(img_data, otr_model, prob=0.2):
  273. log("into otr_interface table_detect")
  274. start_time = time.time()
  275. try:
  276. start_time1 = time.time()
  277. # 二进制数据流转np.ndarray [np.uint8: 8位像素]
  278. img = cv2.imdecode(np.frombuffer(img_data, np.uint8), cv2.IMREAD_COLOR)
  279. # log("into otr_interface table_detect 1")
  280. # cv2.imwrite("111111.jpg", img)
  281. # 将bgr转为rbg
  282. image_np = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
  283. # log("into otr_interface table_detect 2")
  284. # 选择与图片最接近分辨率,以防失真
  285. # best_h, best_w = get_best_predict_size(img)
  286. log("image_np.shape" + str(image_np.shape))
  287. best_h, best_w, _ = image_np.shape
  288. log("otr preprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  289. # 调用模型
  290. # rows, cols = table_line(image_np, otr_model)
  291. start_time1 = time.time()
  292. list_line = table_line(image_np, otr_model, size=(best_w, best_h), prob=prob)
  293. log("otr finish " + str(round(float(time.time()-start_time1), 4)) + "s")
  294. return {"list_line": str(list_line)}
  295. except TimeoutError:
  296. raise TimeoutError
  297. except Exception as e:
  298. log("otr_interface cannot detected table!")
  299. print("otr_interface cannot detected table!", traceback.print_exc())
  300. log("otr postprocess time: " + str(round(float(time.time()-start_time1), 4)) + "s")
  301. return {"list_line": str([])}
  302. class OtrModels:
  303. def __init__(self):
  304. # python文件所在目录
  305. _dir = os.path.abspath(os.path.dirname(os.path.abspath(__file__)))
  306. model_path = _dir + "/models/table-line.h5"
  307. self.otr_model = table_net((None, None, 3), 2)
  308. self.otr_model.load_weights(model_path)
  309. def get_model(self):
  310. return self.otr_model
  311. def test_otr_model(from_remote=True):
  312. _global._init()
  313. from format_convert.convert_image import get_best_predict_size, image_process
  314. if get_platform() == "Windows":
  315. file_path = "C:/Users/Administrator/Desktop/error2.png"
  316. file_path = "C:/Users/Administrator/Downloads/1652672734044.jpg"
  317. else:
  318. file_path = "1.jpg"
  319. image_np = cv2.imread(file_path)
  320. best_h, best_w = get_best_predict_size(image_np)
  321. image_resize = cv2.resize(image_np, (best_w, best_h), interpolation=cv2.INTER_AREA)
  322. cv2.imwrite(file_path, image_resize)
  323. with open(file_path, "rb") as f:
  324. file_bytes = f.read()
  325. file_base64 = base64.b64encode(file_bytes)
  326. _md5 = get_md5_from_bytes(file_bytes)[0]
  327. _global.update({"port": 15010, "md5": _md5})
  328. if from_remote:
  329. file_json = {"data": file_base64, "is_from_pdf": False, "md5": _md5}
  330. # _url = "http://192.168.2.104:18000/otr"
  331. _url = "http://127.0.0.1:18000/otr"
  332. r = json.loads(request_post(_url, file_json))
  333. else:
  334. # otr_model = OtrModels().get_model()
  335. # r = otr(file_base64, otr_model, is_from_pdf=False)
  336. r = image_process(image_resize, file_path)
  337. print(r)
  338. if __name__ == '__main__':
  339. if len(sys.argv) == 2:
  340. port = int(sys.argv[1])
  341. elif len(sys.argv) == 3:
  342. port = int(sys.argv[1])
  343. using_gpu_index = int(sys.argv[2])
  344. else:
  345. port = 18000
  346. using_gpu_index = 0
  347. # app.run(host='0.0.0.0', port=port, processes=1, threaded=False, debug=False)
  348. app.run()
  349. log("OTR running "+str(port))
  350. # test_otr_model(False)
  351. # print(json.dumps([-2]))
  352. # otr_model = OtrModels().get_model()
  353. # otr("11", otr_model)