otr_interface.py 17 KB

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