convert_need_interface.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import base64
  2. import inspect
  3. import json
  4. import logging
  5. import os
  6. import random
  7. import sys
  8. from werkzeug.exceptions import NotFound
  9. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  10. import traceback
  11. import requests
  12. from format_convert import get_memory_info, _global
  13. from format_convert.utils import get_platform, get_sequential_data, judge_error_code, request_post, get_ip_port, \
  14. get_intranet_ip, get_logger, log
  15. from ocr.ocr_interface import ocr, OcrModels
  16. from otr.otr_interface import otr, OtrModels
  17. from format_convert.libreoffice_interface import office_convert
  18. # 远程GPU接口
  19. # # interface_ip_list = ['http://192.168.2.102', 'http://192.168.2.103']
  20. # # interface_ip_list = ['http://172.16.160.65', 'http://172.16.160.64', 'http://172.16.160.66', 'http://172.16.160.67']
  21. # interface_ip_list = ['http://172.16.160.65', 'http://172.16.160.65']
  22. # # ocr_port_list = ["15011", "15013", "15015"]
  23. # # ocr_port_list = ["15011", "15013", "15015", "15017", "15019"]
  24. # # otr_port_list = ["15012", "15014", "15016", "15018", "15020"]
  25. # ocr_port_list = ["15011", "15013", "15015"]
  26. # otr_port_list = ["15012", "15014", "15016"]
  27. # # ocr_port_list = ["15011", "15013", "15015", "15017", "15019", "15021"]
  28. # # otr_port_list = ["15012", "15014", "15016", "15018", "15020", "15022"]
  29. # soffice_port_list = ["16000", "16001", "16002", "16003", "16004", "16005",
  30. # "16006", "16007", "16008", "16009"]
  31. # # ocr_port_list = ["15011", "15013"]
  32. # # otr_port_list = ["15012"]
  33. if get_platform() == "Windows":
  34. FROM_REMOTE = False
  35. else:
  36. FROM_REMOTE = True
  37. def from_office_interface(src_path, dest_path, target_format, retry_times=1, from_remote=FROM_REMOTE):
  38. try:
  39. # Win10跳出超时装饰器
  40. # if get_platform() == "Windows":
  41. # # origin_office_convert = office_convert.__wrapped__
  42. # # file_path = origin_office_convert(src_path, dest_path, target_format, retry_times)
  43. # file_path = office_convert(src_path, dest_path, target_format, retry_times)
  44. # else:
  45. # # 将装饰器包装为一个类,否则多进程Pickle会报错 it's not the same object as xxx 问题,
  46. # # timeout_decorator_obj = my_timeout_decorator.TimeoutClass(office_convert, 180, TimeoutError)
  47. # # file_path = timeout_decorator_obj.run(src_path, dest_path, target_format, retry_times)
  48. #
  49. # file_path = office_convert(src_path, dest_path, target_format, retry_times)
  50. if from_remote:
  51. # 重试
  52. retry_times_1 = 1
  53. retry_times_2 = 2
  54. while retry_times_1 and retry_times_2:
  55. # _ip = ip_pool("soffice", _random=True)
  56. # _port = port_pool("soffice", _random=True)
  57. # _ip = interface_ip_list[0]
  58. # _port = "16002"
  59. # _ip, _port = interface_pool("soffice")
  60. # ip_port = from_schedule_interface("office")
  61. ip_port = interface_pool("office")
  62. if judge_error_code(ip_port):
  63. return ip_port
  64. _url = ip_port + "/soffice"
  65. with open(src_path, "rb") as f:
  66. file_bytes = f.read()
  67. base64_stream = base64.b64encode(file_bytes)
  68. r = json.loads(request_post(_url, {"src_path": src_path,
  69. "dest_path": dest_path,
  70. "file": base64_stream,
  71. "target_format": target_format,
  72. "retry_times": retry_times}, time_out=15))
  73. if type(r) == list:
  74. # 接口连不上换个端口重试
  75. if retry_times_1 <= 1:
  76. return r
  77. else:
  78. retry_times_1 -= 1
  79. log("retry post office_interface... left times " + str(retry_times_1))
  80. continue
  81. file_str = r.get("data")
  82. if judge_error_code(file_str):
  83. if retry_times_2 <= 1:
  84. return file_str
  85. else:
  86. retry_times_2 -= 1
  87. continue
  88. file_bytes = eval(file_str)
  89. uid1 = src_path.split(os.sep)[-1].split(".")[0]
  90. file_path = dest_path + uid1 + "." + target_format
  91. if not os.path.exists(os.path.dirname(file_path)):
  92. os.makedirs(os.path.dirname(file_path), mode=0o777)
  93. with open(file_path, "wb") as f:
  94. f.write(file_bytes)
  95. break
  96. else:
  97. file_path = office_convert(src_path, dest_path, target_format, retry_times)
  98. if judge_error_code(file_path):
  99. return file_path
  100. return file_path
  101. except TimeoutError:
  102. log("from_office_interface timeout error!")
  103. return [-5]
  104. except:
  105. log("from_office_interface error!")
  106. print("from_office_interface", traceback.print_exc())
  107. return [-1]
  108. @get_memory_info.memory_decorator
  109. def from_ocr_interface(image_stream, is_table=False, from_remote=FROM_REMOTE):
  110. log("into from_ocr_interface")
  111. try:
  112. base64_stream = base64.b64encode(image_stream)
  113. # 调用接口
  114. try:
  115. if from_remote:
  116. retry_times_1 = 3
  117. # 重试
  118. while retry_times_1:
  119. # _ip = ip_pool("ocr", _random=True)
  120. # _port = port_pool("ocr", _random=True)
  121. # if _ip == interface_ip_list[1]:
  122. # _port = ocr_port_list[0]
  123. # _ip, _port = interface_pool("ocr")
  124. # ip_port = _ip + ":" + _port
  125. # ip_port = from_schedule_interface("ocr")
  126. ip_port = interface_pool("ocr")
  127. if judge_error_code(ip_port):
  128. return ip_port
  129. _url = ip_port + "/ocr"
  130. r = json.loads(request_post(_url, {"data": base64_stream}, time_out=60))
  131. if type(r) == list:
  132. # 接口连不上换个端口重试
  133. if retry_times_1 <= 1:
  134. if is_table:
  135. return r, r
  136. else:
  137. return r
  138. else:
  139. retry_times_1 -= 1
  140. log("retry post ocr_interface... left times " + str(retry_times_1))
  141. continue
  142. if judge_error_code(r):
  143. return r
  144. break
  145. else:
  146. if globals().get("global_ocr_model") is None:
  147. globals().update({"global_ocr_model": OcrModels().get_model()})
  148. print("=========== init ocr model ===========")
  149. r = ocr(data=base64_stream, ocr_model=globals().get("global_ocr_model"))
  150. except TimeoutError:
  151. if is_table:
  152. return [-5], [-5]
  153. else:
  154. return [-5]
  155. except requests.exceptions.ConnectionError as e:
  156. if is_table:
  157. return [-2], [-2]
  158. else:
  159. return [-2]
  160. _dict = r
  161. text_list = eval(_dict.get("text"))
  162. bbox_list = eval(_dict.get("bbox"))
  163. if text_list is None:
  164. text_list = []
  165. if bbox_list is None:
  166. bbox_list = []
  167. if is_table:
  168. return text_list, bbox_list
  169. else:
  170. if text_list and bbox_list:
  171. text = get_sequential_data(text_list, bbox_list, html=True)
  172. if judge_error_code(text):
  173. return text
  174. else:
  175. text = ""
  176. return text
  177. except Exception as e:
  178. log("from_ocr_interface error!")
  179. # print("from_ocr_interface", e, global_type)
  180. if is_table:
  181. return [-1], [-1]
  182. else:
  183. return [-1]
  184. @get_memory_info.memory_decorator
  185. def from_otr_interface2(image_stream):
  186. log("into from_otr_interface")
  187. try:
  188. base64_stream = base64.b64encode(image_stream)
  189. # 调用接口
  190. try:
  191. if globals().get("global_otr_model") is None:
  192. globals().update({"global_otr_model": OtrModels().get_model()})
  193. print("=========== init otr model ===========")
  194. r = otr(data=base64_stream, otr_model=globals().get("global_otr_model"))
  195. except TimeoutError:
  196. return [-5], [-5], [-5], [-5], [-5]
  197. except requests.exceptions.ConnectionError as e:
  198. log("from_otr_interface")
  199. print("from_otr_interface", traceback.print_exc())
  200. return [-2], [-2], [-2], [-2], [-2]
  201. # 处理结果
  202. _dict = r
  203. points = eval(_dict.get("points"))
  204. split_lines = eval(_dict.get("split_lines"))
  205. bboxes = eval(_dict.get("bboxes"))
  206. outline_points = eval(_dict.get("outline_points"))
  207. lines = eval(_dict.get("lines"))
  208. # print("from_otr_interface len(bboxes)", len(bboxes))
  209. if points is None:
  210. points = []
  211. if split_lines is None:
  212. split_lines = []
  213. if bboxes is None:
  214. bboxes = []
  215. if outline_points is None:
  216. outline_points = []
  217. if lines is None:
  218. lines = []
  219. return points, split_lines, bboxes, outline_points, lines
  220. except Exception as e:
  221. log("from_otr_interface error!")
  222. print("from_otr_interface", traceback.print_exc())
  223. return [-1], [-1], [-1], [-1], [-1]
  224. def from_otr_interface(image_stream, is_from_pdf=False, from_remote=FROM_REMOTE):
  225. log("into from_otr_interface")
  226. try:
  227. base64_stream = base64.b64encode(image_stream)
  228. # 调用接口
  229. try:
  230. if from_remote:
  231. retry_times_1 = 3
  232. # 重试
  233. while retry_times_1:
  234. # _ip = ip_pool("otr", _random=True)
  235. # _port = port_pool("otr", _random=True)
  236. # if _ip == interface_ip_list[1]:
  237. # _port = otr_port_list[0]
  238. ip_port = interface_pool("otr")
  239. # ip_port = from_schedule_interface("otr")
  240. if judge_error_code(ip_port):
  241. return ip_port
  242. _url = ip_port + "/otr"
  243. r = json.loads(request_post(_url, {"data": base64_stream, "is_from_pdf": is_from_pdf}, time_out=60))
  244. if type(r) == list:
  245. # 接口连不上换个端口重试
  246. if retry_times_1 <= 1:
  247. return r
  248. else:
  249. retry_times_1 -= 1
  250. log("retry post otr_interface... left times " + str(retry_times_1))
  251. continue
  252. if judge_error_code(r):
  253. return r
  254. break
  255. else:
  256. if globals().get("global_otr_model") is None:
  257. globals().update({"global_otr_model": OtrModels().get_model()})
  258. print("=========== init otr model ===========")
  259. r = otr(data=base64_stream, otr_model=globals().get("global_otr_model"), is_from_pdf=is_from_pdf)
  260. except TimeoutError:
  261. return [-5]
  262. except requests.exceptions.ConnectionError as e:
  263. log("from_otr_interface")
  264. print("from_otr_interface", traceback.print_exc())
  265. return [-2]
  266. # 处理结果
  267. _dict = r
  268. list_line = eval(_dict.get("list_line"))
  269. return list_line
  270. except Exception as e:
  271. log("from_otr_interface error!")
  272. print("from_otr_interface", traceback.print_exc())
  273. return [-1]
  274. # def from_schedule_interface(interface_type):
  275. # try:
  276. # _ip = "http://" + get_intranet_ip()
  277. # _port = ip_port_dict.get(_ip).get("schedule")[0]
  278. # _url = _ip + ":" + _port + "/schedule"
  279. # data = {"interface_type": interface_type}
  280. # result = json.loads(request_post(_url, data, time_out=10)).get("data")
  281. # if judge_error_code(result):
  282. # return result
  283. # _ip, _port = result
  284. # log("from_schedule_interface " + _ip + " " + _port)
  285. # return _ip + ":" + _port
  286. # except requests.exceptions.ConnectionError as e:
  287. # log("from_schedule_interface ConnectionError")
  288. # return [-2]
  289. # except:
  290. # log("from_schedule_interface error!")
  291. # traceback.print_exc()
  292. # return [-1]
  293. def interface_pool(interface_type):
  294. ip_port_flag = _global.get("ip_port_flag")
  295. ip_port_dict = _global.get("ip_port")
  296. log(str(_global.get("ip_port_flag")))
  297. try:
  298. # 负载均衡, 选取ip
  299. interface_load_list = []
  300. for _ip in ip_port_flag.keys():
  301. if ip_port_dict.get(_ip).get(interface_type):
  302. load_scale = ip_port_flag.get(_ip).get(interface_type) / len(ip_port_dict.get(_ip).get(interface_type))
  303. interface_load_list.append([_ip, load_scale])
  304. if not interface_load_list:
  305. raise NotFound
  306. interface_load_list.sort(key=lambda x: x[-1])
  307. _ip = interface_load_list[0][0]
  308. # 负载均衡, 选取port
  309. ip_type_cnt = ip_port_flag.get(_ip).get(interface_type)
  310. ip_type_total = len(ip_port_dict.get(_ip).get(interface_type))
  311. if ip_type_cnt == 0:
  312. ip_type_cnt = random.randint(0, ip_type_total-1)
  313. port_index = ip_type_cnt % ip_type_total
  314. _port = ip_port_dict.get(_ip).get(interface_type)[port_index]
  315. # 更新flag
  316. current_flag = ip_type_cnt
  317. if current_flag >= 10000:
  318. ip_port_flag[_ip][interface_type] = 0
  319. else:
  320. ip_port_flag[_ip][interface_type] = current_flag + 1
  321. _global.update({"ip_port_flag": ip_port_flag})
  322. log(str(_global.get("ip_port_flag")))
  323. ip_port = _ip + ":" + str(_port)
  324. log(ip_port)
  325. return ip_port
  326. except NotFound:
  327. log("cannot read ip from config! checkout config")
  328. return [-2]
  329. except:
  330. traceback.print_exc()
  331. return [-1]
  332. # def ip_pool(interface_type, _random=False):
  333. # ip_flag_name = interface_type + '_ip_flag'
  334. # ip_flag = globals().get(ip_flag_name)
  335. # if ip_flag is None:
  336. # if _random:
  337. # _r = random.randint(0, len(interface_ip_list)-1)
  338. # ip_flag = _r
  339. # globals().update({ip_flag_name: ip_flag})
  340. # ip_index = _r
  341. # else:
  342. # ip_flag = 0
  343. # globals().update({ip_flag_name: ip_flag})
  344. # ip_index = 0
  345. # else:
  346. # ip_index = ip_flag % len(interface_ip_list)
  347. # ip_flag += 1
  348. #
  349. # if ip_flag >= 10000:
  350. # ip_flag = 0
  351. # globals().update({ip_flag_name: ip_flag})
  352. #
  353. # log("ip_pool " + interface_type + " " + str(ip_flag) + " " + str(interface_ip_list[ip_index]))
  354. # return interface_ip_list[ip_index]
  355. #
  356. #
  357. # def port_pool(interface_type, _random=False):
  358. # port_flag_name = interface_type + '_port_flag'
  359. #
  360. # port_flag = globals().get(port_flag_name)
  361. # if port_flag is None:
  362. # if _random:
  363. # if interface_type == "ocr":
  364. # _r = random.randint(0, len(ocr_port_list)-1)
  365. # elif interface_type == "otr":
  366. # _r = random.randint(0, len(otr_port_list)-1)
  367. # else:
  368. # _r = random.randint(0, len(soffice_port_list)-1)
  369. # port_flag = _r
  370. # globals().update({port_flag_name: port_flag})
  371. # port_index = _r
  372. # else:
  373. # port_flag = 0
  374. # globals().update({port_flag_name: port_flag})
  375. # port_index = 0
  376. # else:
  377. # if interface_type == "ocr":
  378. # port_index = port_flag % len(ocr_port_list)
  379. # elif interface_type == "otr":
  380. # port_index = port_flag % len(otr_port_list)
  381. # else:
  382. # port_index = port_flag % len(soffice_port_list)
  383. # port_flag += 1
  384. #
  385. # if port_flag >= 10000:
  386. # port_flag = 0
  387. # globals().update({port_flag_name: port_flag})
  388. #
  389. # if interface_type == "ocr":
  390. # log("port_pool " + interface_type + " " + str(port_flag) + " " + ocr_port_list[port_index])
  391. # return ocr_port_list[port_index]
  392. # elif interface_type == "otr":
  393. # log("port_pool " + interface_type + " " + str(port_flag) + " " + otr_port_list[port_index])
  394. # return otr_port_list[port_index]
  395. # else:
  396. # log("port_pool " + interface_type + " " + str(port_flag) + " " + soffice_port_list[port_index])
  397. # return soffice_port_list[port_index]