otr_interface.py 16 KB

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