convert_need_interface.py 30 KB

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