otr_interface.py 17 KB

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