convert_need_interface.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  1. # encoding=utf8
  2. import base64
  3. import json
  4. import multiprocessing
  5. import os
  6. import pickle
  7. import random
  8. import sys
  9. import time
  10. import uuid
  11. import cv2
  12. import torch
  13. from werkzeug.exceptions import NotFound
  14. from tika_.tika_interface import tika_interface
  15. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  16. from botr.yolov8.yolo_interface import yolo
  17. from botr.yolov8.model import Predictor
  18. from atc.atc_interface import AtcModels, atc
  19. from idc.idc_interface import IdcModels, idc
  20. from isr.isr_interface import IsrModels, isr
  21. import traceback
  22. import requests
  23. from format_convert import _global
  24. from format_convert.utils import get_platform, get_sequential_data, judge_error_code, request_post, get_ip_port, \
  25. get_intranet_ip, get_logger, log, get_args_from_config, get_using_ip, np2bytes, set_flask_global
  26. from ocr.ocr_interface import ocr, OcrModels
  27. from otr.otr_interface import otr, OtrModels
  28. from format_convert.libreoffice_interface import office_convert
  29. import numpy as np
  30. from config.max_compute_config import MAX_COMPUTE
  31. if get_platform() == "Windows":
  32. FROM_REMOTE = False
  33. only_test_ocr = False
  34. if only_test_ocr:
  35. ip_port_flag = {}
  36. ip_port_dict = get_ip_port()
  37. for _k in ip_port_dict.keys():
  38. ip_port_flag.update({_k: {"ocr": 0,
  39. "otr": 0,
  40. "convert": 0,
  41. "office": 0
  42. }})
  43. _global.update({"ip_port_flag": ip_port_flag})
  44. ip_port_dict["http://127.0.0.1"]["ocr"] = ["17000"]
  45. ip_port_dict["http://127.0.0.1"]["otr"] = ["18000"]
  46. _global.update({"ip_port": ip_port_dict})
  47. else:
  48. FROM_REMOTE = True
  49. if MAX_COMPUTE:
  50. FROM_REMOTE = False
  51. lock = multiprocessing.RLock()
  52. # 连接redis数据库
  53. # redis_db = redis.StrictRedis(host='192.168.2.103', port='6379',
  54. # db=1, password='bidi123456', health_check_interval=300)
  55. redis_db = None
  56. def from_office_interface_240606(src_path, dest_path, target_format, retry_times=1, from_remote=FROM_REMOTE):
  57. try:
  58. # Win10跳出超时装饰器
  59. # if get_platform() == "Windows":
  60. # # origin_office_convert = office_convert.__wrapped__
  61. # # file_path = origin_office_convert(src_path, dest_path, target_format, retry_times)
  62. # file_path = office_convert(src_path, dest_path, target_format, retry_times)
  63. # else:
  64. # # 将装饰器包装为一个类,否则多进程Pickle会报错 it's not the same object as xxx 问题,
  65. # # timeout_decorator_obj = my_timeout_decorator.TimeoutClass(office_convert, 180, TimeoutError)
  66. # # file_path = timeout_decorator_obj.run(src_path, dest_path, target_format, retry_times)
  67. #
  68. # file_path = office_convert(src_path, dest_path, target_format, retry_times)
  69. if from_remote:
  70. # 重试
  71. retry_times_1 = 1
  72. retry_times_2 = 2
  73. while retry_times_1 and retry_times_2:
  74. # _ip = ip_pool("soffice", _random=True)
  75. # _port = port_pool("soffice", _random=True)
  76. # _ip = interface_ip_list[0]
  77. # _port = "16002"
  78. # _ip, _port = interface_pool("soffice")
  79. # ip_port = from_schedule_interface("office")
  80. ip_port = interface_pool_gunicorn("office")
  81. if judge_error_code(ip_port):
  82. return ip_port
  83. _url = ip_port + "/soffice"
  84. with open(src_path, "rb") as f:
  85. file_bytes = f.read()
  86. base64_stream = base64.b64encode(file_bytes)
  87. start_time = time.time()
  88. log('office _url ' + str(_url))
  89. r = json.loads(request_post(_url, {"src_path": src_path,
  90. "dest_path": dest_path,
  91. "file": base64_stream,
  92. "target_format": target_format,
  93. "retry_times": retry_times}, time_out=25))
  94. log("get office_interface return")
  95. log("office use time " + str(time.time()-start_time))
  96. if type(r) == list:
  97. # 接口连不上换个端口重试
  98. if retry_times_1 <= 1:
  99. return r
  100. else:
  101. retry_times_1 -= 1
  102. log("retry post office_interface... left times " + str(retry_times_1))
  103. continue
  104. file_str = r.get("data")
  105. if judge_error_code(file_str):
  106. if retry_times_2 <= 1:
  107. return file_str
  108. else:
  109. retry_times_2 -= 1
  110. continue
  111. file_bytes = eval(file_str)
  112. uid1 = src_path.split(os.sep)[-1].split(".")[0]
  113. file_path = dest_path + uid1 + "." + target_format
  114. if not os.path.exists(os.path.dirname(file_path)):
  115. os.makedirs(os.path.dirname(file_path), mode=0o777)
  116. with open(file_path, "wb") as f:
  117. f.write(file_bytes)
  118. break
  119. else:
  120. file_path = office_convert(src_path, dest_path, target_format, retry_times)
  121. if judge_error_code(file_path):
  122. return file_path
  123. return file_path
  124. except TimeoutError:
  125. log("from_office_interface timeout error!")
  126. return [-5]
  127. except:
  128. log("from_office_interface error!")
  129. print("from_office_interface", traceback.print_exc())
  130. return [-1]
  131. def from_office_interface(src_path, dest_path, target_format, retry_times=1, from_remote=FROM_REMOTE):
  132. try:
  133. if from_remote:
  134. # 重试
  135. while retry_times >= 0:
  136. ip_port = interface_pool_gunicorn("office")
  137. if judge_error_code(ip_port):
  138. return ip_port
  139. _url = ip_port + "/soffice"
  140. with open(src_path, "rb") as f:
  141. file_bytes = f.read()
  142. base64_stream = base64.b64encode(file_bytes)
  143. start_time = time.time()
  144. log('office _url ' + str(_url))
  145. r = json.loads(request_post(_url, {"src_path": src_path,
  146. "dest_path": dest_path,
  147. "file": base64_stream,
  148. "target_format": target_format,
  149. "retry_times": retry_times}, time_out=25))
  150. log("get office_interface return, use time " + str(time.time()-start_time))
  151. # 报错信息
  152. if type(r) == list:
  153. file_path = r
  154. # 拒绝连接,换个端口
  155. if r == [-22]:
  156. log("retry post office_interface... left times " + str(retry_times))
  157. retry_times -= 1
  158. continue
  159. else:
  160. return r
  161. file_str = r.get("data")
  162. if judge_error_code(file_str):
  163. return file_str
  164. uid1 = src_path.split(os.sep)[-1].split(".")[0]
  165. file_path = dest_path + uid1 + "." + target_format
  166. file_bytes = eval(file_str)
  167. if not os.path.exists(os.path.dirname(file_path)):
  168. os.makedirs(os.path.dirname(file_path), mode=0o777)
  169. with open(file_path, "wb") as f:
  170. f.write(file_bytes)
  171. break
  172. else:
  173. file_path = office_convert(src_path, dest_path, target_format, retry_times)
  174. if judge_error_code(file_path):
  175. return file_path
  176. return file_path
  177. except TimeoutError:
  178. log("from_office_interface timeout error!")
  179. return [-5]
  180. except:
  181. log("from_office_interface error!")
  182. traceback.print_exc()
  183. return [-1]
  184. def from_tika_interface(src_path, from_remote=FROM_REMOTE):
  185. log("into from_tika_interface")
  186. start_time = time.time()
  187. try:
  188. # 调用接口
  189. try:
  190. if from_remote:
  191. retry_times_1 = 2
  192. # 重试
  193. while retry_times_1:
  194. ip_port = interface_pool_gunicorn("tika")
  195. if judge_error_code(ip_port):
  196. return ip_port
  197. _url = ip_port + "/tika"
  198. r = json.loads(request_post(_url, {"data": src_path,
  199. "md5": _global.get("md5")},
  200. time_out=10))
  201. log("get tika_interface return " + _url)
  202. if type(r) == list:
  203. # 接口连不上换个端口重试
  204. if retry_times_1 <= 1:
  205. return r
  206. else:
  207. retry_times_1 -= 1
  208. log("retry post tika_interface... left times " + str(retry_times_1))
  209. continue
  210. if judge_error_code(r):
  211. return r
  212. break
  213. else:
  214. r = tika_interface(src_path)
  215. except TimeoutError:
  216. return [-5]
  217. except requests.exceptions.ConnectionError as e:
  218. return [-2]
  219. _dict = r
  220. html = _dict.get("html")
  221. log("from_tika_interface cost time " + str(time.time()-start_time))
  222. return html
  223. except Exception as e:
  224. log("from_tika_interface error!")
  225. traceback.print_exc()
  226. return [-11]
  227. def from_ocr_interface(image_stream, is_table=0, only_rec=0, from_remote=FROM_REMOTE):
  228. log("into from_ocr_interface")
  229. try:
  230. base64_stream = base64.b64encode(image_stream)
  231. # 调用接口
  232. try:
  233. if from_remote:
  234. retry_times_1 = 3
  235. # 重试
  236. while retry_times_1:
  237. ip_port = interface_pool_gunicorn("ocr")
  238. if judge_error_code(ip_port):
  239. return ip_port
  240. _url = ip_port + "/ocr"
  241. r = json.loads(request_post(_url, {"data": base64_stream,
  242. "md5": _global.get("md5"),
  243. "only_rec": only_rec
  244. },
  245. time_out=60))
  246. log("get ocr_interface return")
  247. if type(r) == list:
  248. # 接口连不上换个端口重试
  249. if retry_times_1 <= 1:
  250. if is_table:
  251. return r, r
  252. else:
  253. return r
  254. else:
  255. retry_times_1 -= 1
  256. log("retry post ocr_interface... left times " + str(retry_times_1))
  257. continue
  258. if judge_error_code(r):
  259. return r
  260. break
  261. else:
  262. if globals().get("global_ocr_model") is None:
  263. print("=========== init ocr model ===========")
  264. globals().update({"global_ocr_model": OcrModels().get_model()})
  265. r = ocr(data=base64_stream, ocr_model=globals().get("global_ocr_model"), only_rec=only_rec)
  266. except TimeoutError:
  267. if is_table:
  268. return [-5], [-5]
  269. else:
  270. return [-5]
  271. except requests.exceptions.ConnectionError as e:
  272. if is_table:
  273. return [-2], [-2]
  274. else:
  275. return [-2]
  276. _dict = r
  277. text_list = eval(_dict.get("text"))
  278. bbox_list = eval(_dict.get("bbox"))
  279. if text_list is None:
  280. text_list = []
  281. if bbox_list is None:
  282. bbox_list = []
  283. if is_table:
  284. return text_list, bbox_list
  285. else:
  286. if text_list and bbox_list:
  287. text = get_sequential_data(text_list, bbox_list, html=True)
  288. if judge_error_code(text):
  289. return text
  290. else:
  291. text = ""
  292. return text
  293. except Exception as e:
  294. log("from_ocr_interface error!")
  295. log(str(traceback.print_exc()))
  296. traceback.print_exc()
  297. # print("from_ocr_interface", e, global_type)
  298. if is_table:
  299. return [-1], [-1]
  300. else:
  301. return [-1]
  302. def from_gpu_interface_redis(_dict, model_type, predictor_type):
  303. log("into from_gpu_interface")
  304. start_time = time.time()
  305. try:
  306. # 调用接口
  307. _uuid = uuid.uuid1().hex
  308. _dict.update({"predictor_type": predictor_type, "model_type": model_type,
  309. "uuid": _uuid})
  310. _time = time.time()
  311. log("pickle.dumps(_dict)" + str(_dict))
  312. redis_db.rpush("producer_"+model_type, pickle.dumps(_dict))
  313. log("producer_" + model_type + " len " + str(redis_db.llen("producer_" + model_type)))
  314. log("to producer_" + model_type + " time " + str(time.time()-_time))
  315. _time = time.time()
  316. time_out = 300
  317. while True:
  318. time.sleep(0.2)
  319. if time.time() - _time > time_out:
  320. raise Exception
  321. if redis_db.hexists("consumer_"+model_type, _uuid):
  322. time1 = time.time()
  323. result = redis_db.hget("consumer_"+model_type, _uuid)
  324. log("from consumer_"+model_type + " time " + str(time.time()-time1))
  325. break
  326. result = pickle.loads(result)
  327. log("from_gpu_interface finish - size " + str(sys.getsizeof(_dict)) + " - time " + str(time.time()-start_time))
  328. return result
  329. except Exception as e:
  330. log("from_gpu_interface error!")
  331. log("from_gpu_interface failed " + str(time.time()-start_time))
  332. traceback.print_exc()
  333. return [-2]
  334. def from_otr_interface(image_stream, is_from_pdf=False, from_remote=FROM_REMOTE):
  335. log("into from_otr_interface")
  336. try:
  337. base64_stream = base64.b64encode(image_stream)
  338. # 调用接口
  339. try:
  340. if from_remote:
  341. log("from remote")
  342. retry_times_1 = 3
  343. # 重试
  344. while retry_times_1:
  345. # _ip = ip_pool("otr", _random=True)
  346. # _port = port_pool("otr", _random=True)
  347. # if _ip == interface_ip_list[1]:
  348. # _port = otr_port_list[0]
  349. ip_port = interface_pool_gunicorn("otr")
  350. # ip_port = from_schedule_interface("otr")
  351. if judge_error_code(ip_port):
  352. return ip_port
  353. _url = ip_port + "/otr"
  354. r = json.loads(request_post(_url, {"data": base64_stream,
  355. "is_from_pdf": is_from_pdf,
  356. "md5": _global.get("md5")}, time_out=60))
  357. log("get otr_interface return")
  358. if type(r) == list:
  359. # 接口连不上换个端口重试
  360. if retry_times_1 <= 1:
  361. return r
  362. else:
  363. retry_times_1 -= 1
  364. log("retry post otr_interface... left times " + str(retry_times_1))
  365. continue
  366. if judge_error_code(r):
  367. return r
  368. break
  369. else:
  370. log("from local")
  371. log("otr_model " + str(globals().get("global_otr_model")))
  372. if globals().get("global_otr_model") is None:
  373. print("=========== init otr model ===========")
  374. globals().update({"global_otr_model": OtrModels().get_model()})
  375. log("init finish")
  376. r = otr(data=base64_stream, otr_model=globals().get("global_otr_model"), is_from_pdf=is_from_pdf)
  377. # r = otr(data=base64_stream, otr_model=None, is_from_pdf=is_from_pdf)
  378. except TimeoutError:
  379. return [-5]
  380. except requests.exceptions.ConnectionError as e:
  381. log("from_otr_interface")
  382. print("from_otr_interface", traceback.print_exc())
  383. return [-2]
  384. # 处理结果
  385. _dict = r
  386. list_line = eval(_dict.get("list_line"))
  387. return list_line
  388. except Exception as e:
  389. log("from_otr_interface error!")
  390. print("from_otr_interface", traceback.print_exc())
  391. return [-1]
  392. def from_isr_interface(image_stream, from_remote=FROM_REMOTE):
  393. log("into from_isr_interface")
  394. # os.environ["CUDA_VISIBLE_DEVICES"] = "0"
  395. start_time = time.time()
  396. try:
  397. base64_stream = base64.b64encode(image_stream)
  398. # 调用接口
  399. try:
  400. if from_remote:
  401. retry_times_1 = 3
  402. # 重试
  403. while retry_times_1:
  404. ip_port = interface_pool_gunicorn("isr")
  405. if judge_error_code(ip_port):
  406. return ip_port
  407. _url = ip_port + "/isr"
  408. r = json.loads(request_post(_url, {"data": base64_stream,
  409. "md5": _global.get("md5")},
  410. time_out=60))
  411. log("get isr_interface return")
  412. if type(r) == list:
  413. # 接口连不上换个端口重试
  414. if retry_times_1 <= 1:
  415. return r
  416. else:
  417. retry_times_1 -= 1
  418. log("retry post isr_interface... left times " + str(retry_times_1))
  419. continue
  420. if judge_error_code(r):
  421. return r
  422. break
  423. else:
  424. if globals().get("global_isr_model") is None:
  425. print("=========== init isr model ===========")
  426. isr_yolo_model, isr_model = IsrModels().get_model()
  427. globals().update({"global_isr_yolo_model": isr_yolo_model})
  428. globals().update({"global_isr_model": isr_model})
  429. r = isr(data=base64_stream,
  430. isr_yolo_model=globals().get("global_isr_yolo_model"),
  431. isr_model=globals().get("global_isr_model"))
  432. except TimeoutError:
  433. return [-5]
  434. except requests.exceptions.ConnectionError as e:
  435. return [-2]
  436. _dict = r
  437. if from_remote:
  438. image_string = _dict.get("image")
  439. if judge_error_code(image_string):
  440. return image_string
  441. # [1]代表检测不到印章,直接返回
  442. if isinstance(image_string, list) and image_string == [1]:
  443. return image_string
  444. image_base64 = image_string.encode("utf-8")
  445. image_bytes = base64.b64decode(image_base64)
  446. buffer = np.frombuffer(image_bytes, dtype=np.uint8)
  447. image_np = cv2.imdecode(buffer, 1)
  448. else:
  449. image_np = _dict.get("image")
  450. log("from_isr_interface cost time " + str(time.time()-start_time))
  451. return image_np
  452. except Exception as e:
  453. log("from_isr_interface error!")
  454. traceback.print_exc()
  455. return [-11]
  456. finally:
  457. # os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
  458. pass
  459. def from_idc_interface(image_stream, from_remote=FROM_REMOTE):
  460. log("into from_idc_interface")
  461. start_time = time.time()
  462. try:
  463. base64_stream = base64.b64encode(image_stream)
  464. # 调用接口
  465. try:
  466. if from_remote:
  467. retry_times_1 = 3
  468. # 重试
  469. while retry_times_1:
  470. ip_port = interface_pool_gunicorn("idc")
  471. if judge_error_code(ip_port):
  472. return ip_port
  473. _url = ip_port + "/idc"
  474. r = json.loads(request_post(_url, {"data": base64_stream,
  475. "md5": _global.get("md5")},
  476. time_out=60))
  477. log("get idc_interface return")
  478. if type(r) == list:
  479. # 接口连不上换个端口重试
  480. if retry_times_1 <= 1:
  481. return r
  482. else:
  483. retry_times_1 -= 1
  484. log("retry post idc_interface... left times " + str(retry_times_1))
  485. continue
  486. if judge_error_code(r):
  487. return r
  488. break
  489. else:
  490. if globals().get("global_idc_model") is None:
  491. print("=========== init idc model ===========")
  492. idc_model = IdcModels().get_model()
  493. globals().update({"global_idc_model": idc_model})
  494. r = idc(data=base64_stream,
  495. model=globals().get("global_idc_model"))
  496. except TimeoutError:
  497. return [-5]
  498. except requests.exceptions.ConnectionError as e:
  499. return [-2]
  500. _dict = r
  501. angle = _dict.get("angle")
  502. log("from_idc_interface cost time " + str(time.time()-start_time))
  503. return angle
  504. except Exception as e:
  505. log("from_idc_interface error!")
  506. traceback.print_exc()
  507. return [-11]
  508. def from_atc_interface(text, from_remote=FROM_REMOTE):
  509. log("into from_atc_interface")
  510. start_time = time.time()
  511. try:
  512. # 调用接口
  513. try:
  514. if from_remote:
  515. retry_times_1 = 3
  516. # 重试
  517. while retry_times_1:
  518. ip_port = interface_pool_gunicorn("atc")
  519. if judge_error_code(ip_port):
  520. return ip_port
  521. _url = ip_port + "/atc"
  522. r = json.loads(request_post(_url, {"data": text,
  523. "md5": _global.get("md5")},
  524. time_out=60))
  525. log("get atc_interface return")
  526. if type(r) == list:
  527. # 接口连不上换个端口重试
  528. if retry_times_1 <= 1:
  529. return r
  530. else:
  531. retry_times_1 -= 1
  532. log("retry post atc_interface... left times " + str(retry_times_1))
  533. continue
  534. if judge_error_code(r):
  535. return r
  536. break
  537. else:
  538. if globals().get("global_atc_model") is None:
  539. print("=========== init atc model ===========")
  540. atc_model = AtcModels().get_model()
  541. globals().update({"global_atc_model": atc_model})
  542. r = atc(data=text,
  543. model=globals().get("global_atc_model"))
  544. except TimeoutError:
  545. return [-5]
  546. except requests.exceptions.ConnectionError as e:
  547. return [-2]
  548. _dict = r
  549. classification = _dict.get("classification")
  550. log("from_atc_interface cost time " + str(time.time()-start_time))
  551. return classification
  552. except Exception as e:
  553. log("from_atc_interface error!")
  554. traceback.print_exc()
  555. return [-11]
  556. def from_yolo_interface(image_stream, from_remote=FROM_REMOTE):
  557. log("into from_yolo_interface")
  558. start_time = time.time()
  559. try:
  560. base64_stream = base64.b64encode(image_stream)
  561. # 调用接口
  562. try:
  563. if from_remote:
  564. retry_times_1 = 3
  565. # 重试
  566. while retry_times_1:
  567. ip_port = interface_pool_gunicorn("yolo")
  568. if judge_error_code(ip_port):
  569. return ip_port
  570. _url = ip_port + "/yolo"
  571. log('yolo _url ' + _url)
  572. r = json.loads(request_post(_url, {"data": base64_stream,
  573. "md5": _global.get("md5")},
  574. time_out=60))
  575. log("get yolo_interface return")
  576. if type(r) == list:
  577. # 接口连不上换个端口重试
  578. if retry_times_1 <= 1:
  579. return r
  580. else:
  581. retry_times_1 -= 1
  582. log("retry post yolo_interface... left times " + str(retry_times_1))
  583. continue
  584. if judge_error_code(r):
  585. return r
  586. break
  587. else:
  588. if globals().get("global_yolo_predictor") is None:
  589. print("=========== init yolo model ===========")
  590. ROOT = os.path.abspath(os.path.dirname(__file__)) + '/../'
  591. model_path = ROOT + 'botr/yolov8/weights.pt'
  592. image_size = 640
  593. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  594. yolo_predictor = Predictor(image_size, device, model_path)
  595. globals().update({"global_yolo_predictor": yolo_predictor})
  596. r = yolo(data=base64_stream,
  597. predictor=globals().get("global_yolo_predictor"))
  598. except TimeoutError:
  599. return [-5]
  600. except requests.exceptions.ConnectionError as e:
  601. return [-2]
  602. _dict = r
  603. b_table_list = _dict.get("b_table_list")
  604. log("from_yolo_interface cost time " + str(time.time()-start_time))
  605. return b_table_list
  606. except Exception as e:
  607. log("from_yolo_interface error!")
  608. traceback.print_exc()
  609. return [-11]
  610. def interface_pool_gunicorn(interface_type):
  611. if get_platform() == 'Windows':
  612. set_flask_global()
  613. ip_port_flag_dict = _global.get("ip_port_flag")
  614. ip_port_dict = _global.get("ip_port")
  615. try:
  616. if ip_port_dict is None or ip_port_flag_dict is None:
  617. raise NotFound
  618. # 负载均衡, 选取有该接口的ip
  619. min_cnt = 10000.
  620. interface_cnt = 0
  621. _ip = None
  622. port_list = []
  623. for key in ip_port_flag_dict.keys():
  624. temp_port_list = get_args_from_config(ip_port_dict, key, interface_type)
  625. # print('temp_port_list', temp_port_list)
  626. if not temp_port_list:
  627. continue
  628. # 该ip下的该接口总数量(可能有多gpu接口)
  629. _port_list, _port_num_list, _ = temp_port_list[0]
  630. # print('_port_num_list', _port_num_list)
  631. total_port_num = sum(_port_num_list)
  632. if total_port_num == 0:
  633. continue
  634. interface_cnt = ip_port_flag_dict.get(key).get(interface_type)
  635. if interface_cnt is not None and interface_cnt / total_port_num < min_cnt:
  636. _ip = key
  637. min_cnt = interface_cnt / len(temp_port_list[0])
  638. # 选定ip,设置gpu的接口候选比例
  639. gpu_port_list = []
  640. for k in range(len(_port_list)):
  641. gpu_port_list += [_port_list[k]] * _port_num_list[k]
  642. port_list = gpu_port_list
  643. # port_list = temp_port_list[0]
  644. # 选取端口
  645. if interface_type == "office":
  646. if len(port_list) == 0:
  647. raise ConnectionError
  648. port_list = [str(port_list[k] + k) for k in range(len(port_list))]
  649. # 刚开始随机,后续求余
  650. if min_cnt == 0:
  651. _port = port_list[random.randint(0, len(port_list)-1)]
  652. ip_port_flag_dict[_ip][interface_type] = int(_port[-2:])
  653. else:
  654. _port = port_list[interface_cnt % len(port_list)]
  655. else:
  656. # 使用gunicorn则随机选
  657. _port = random.choice(port_list)
  658. # 更新flag
  659. if ip_port_flag_dict.get(_ip).get(interface_type) >= 10000:
  660. ip_port_flag_dict[_ip][interface_type] = 0
  661. else:
  662. ip_port_flag_dict[_ip][interface_type] += 1
  663. _global.update({"ip_port_flag": ip_port_flag_dict})
  664. ip_port = _ip + ":" + str(_port)
  665. log(interface_type)
  666. log(ip_port)
  667. return ip_port
  668. except NotFound:
  669. log("ip_port or ip_port_dict is None! checkout config")
  670. return [-2]
  671. except ConnectionError:
  672. log('no office interface running!')
  673. return [-15]
  674. except:
  675. traceback.print_exc()
  676. return [-1]
  677. if __name__ == "__main__":
  678. _global._init()
  679. set_flask_global()
  680. _img = cv2.imread(r"C:/Users/Administrator/Desktop/test_b_table/error11.png")
  681. _img_bytes = np2bytes(_img)
  682. b_list = from_yolo_interface(_img_bytes, from_remote=True)
  683. for l in b_list:
  684. for b in l:
  685. cv2.rectangle(_img, (int(b[0]), int(b[1])), (int(b[2]), int(b[3])), (0, 0, 255), 2)
  686. cv2.namedWindow('img', cv2.WINDOW_NORMAL)
  687. cv2.imshow('img', _img)
  688. cv2.waitKey(0)