convert.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. #-*- coding: utf-8 -*-
  2. import gc
  3. import json
  4. import sys
  5. import os
  6. import tracemalloc
  7. from io import BytesIO
  8. import objgraph
  9. sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
  10. # 强制tf使用cpu
  11. os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
  12. from format_convert.utils import judge_error_code, request_post, get_intranet_ip, get_ip_port, get_logger, log, \
  13. set_flask_global, get_md5_from_bytes, memory_decorator
  14. from format_convert.convert_doc import doc2text, DocConvert
  15. from format_convert.convert_docx import docx2text, DocxConvert
  16. from format_convert.convert_image import picture2text, ImageConvert
  17. from format_convert.convert_pdf import pdf2text, PDFConvert
  18. from format_convert.convert_rar import rar2text, RarConvert
  19. from format_convert.convert_swf import swf2text, SwfConvert
  20. from format_convert.convert_txt import txt2text, TxtConvert
  21. from format_convert.convert_xls import xls2text, XlsConvert
  22. from format_convert.convert_xlsx import xlsx2text, XlsxConvert
  23. from format_convert.convert_zip import zip2text, ZipConvert
  24. import hashlib
  25. from format_convert.judge_platform import get_platform
  26. from ocr import ocr_interface
  27. from otr import otr_interface
  28. import re
  29. import shutil
  30. import base64
  31. import time
  32. import uuid
  33. import logging
  34. from bs4 import BeautifulSoup
  35. from flask import Flask, request, g
  36. import inspect
  37. logging.getLogger("pdfminer").setLevel(logging.WARNING)
  38. from format_convert.table_correct import *
  39. import logging
  40. from format_convert.wrapt_timeout_decorator import *
  41. from format_convert import _global
  42. port_num = [0]
  43. def choose_port():
  44. process_num = 4
  45. if port_num[0] % process_num == 0:
  46. _url = local_url + ":15011"
  47. elif port_num[0] % process_num == 1:
  48. _url = local_url + ":15012"
  49. elif port_num[0] % process_num == 2:
  50. _url = local_url + ":15013"
  51. elif port_num[0] % process_num == 3:
  52. _url = local_url + ":15014"
  53. port_num[0] = port_num[0] + 1
  54. return _url
  55. @memory_decorator
  56. def getText(_type, path_or_stream):
  57. @timeout(300, timeout_exception=TimeoutError, use_signals=False)
  58. def get_html_1(_class):
  59. return _class.get_html()
  60. @timeout(600, timeout_exception=TimeoutError, use_signals=False)
  61. def get_html_2(_class):
  62. return _class.get_html()
  63. log("file type - " + _type)
  64. try:
  65. ss = path_or_stream.split(".")
  66. unique_type_dir = ss[-2] + "_" + ss[-1] + os.sep
  67. except:
  68. unique_type_dir = path_or_stream + "_" + _type + os.sep
  69. if _type == "pdf":
  70. # return PDFConvert(path_or_stream, unique_type_dir).get_html()
  71. return get_html_1(PDFConvert(path_or_stream, unique_type_dir))
  72. if _type == "docx":
  73. # return DocxConvert(path_or_stream, unique_type_dir).get_html()
  74. return get_html_1(DocxConvert(path_or_stream, unique_type_dir))
  75. if _type == "zip":
  76. return ZipConvert(path_or_stream, unique_type_dir).get_html()
  77. # return get_html_2(ZipConvert(path_or_stream, unique_type_dir))
  78. if _type == "rar":
  79. return RarConvert(path_or_stream, unique_type_dir).get_html()
  80. # return get_html_2(RarConvert(path_or_stream, unique_type_dir))
  81. if _type == "xlsx":
  82. # return XlsxConvert(path_or_stream, unique_type_dir).get_html()
  83. return get_html_1(XlsxConvert(path_or_stream, unique_type_dir))
  84. if _type == "xls":
  85. # return XlsConvert(path_or_stream, unique_type_dir).get_html()
  86. return get_html_1(XlsConvert(path_or_stream, unique_type_dir))
  87. if _type == "doc":
  88. # return DocConvert(path_or_stream, unique_type_dir).get_html()
  89. return get_html_1(DocConvert(path_or_stream, unique_type_dir))
  90. if _type == "jpg" or _type == "png" or _type == "jpeg":
  91. # return ImageConvert(path_or_stream, unique_type_dir).get_html()
  92. return get_html_1(ImageConvert(path_or_stream, unique_type_dir))
  93. if _type == "swf":
  94. # return SwfConvert(path_or_stream, unique_type_dir).get_html()
  95. return get_html_1(SwfConvert(path_or_stream, unique_type_dir))
  96. if _type == "txt":
  97. # return TxtConvert(path_or_stream, unique_type_dir).get_html()
  98. return get_html_1(TxtConvert(path_or_stream, unique_type_dir))
  99. return [""]
  100. def to_html(path, text):
  101. with open(path, 'w',encoding="utf8") as f:
  102. f.write("<!DOCTYPE HTML>")
  103. f.write('<head><meta charset="UTF-8"></head>')
  104. f.write("<body>")
  105. f.write(text)
  106. f.write("</body>")
  107. def resize_image(image_path, size):
  108. try:
  109. image_np = cv2.imread(image_path)
  110. # print(image_np.shape)
  111. width = image_np.shape[1]
  112. height = image_np.shape[0]
  113. h_w_rate = height / width
  114. # width_standard = 900
  115. # height_standard = 1400
  116. width_standard = size[1]
  117. height_standard = size[0]
  118. width_new = int(height_standard / h_w_rate)
  119. height_new = int(width_standard * h_w_rate)
  120. if width > width_standard:
  121. image_np = cv2.resize(image_np, (width_standard, height_new))
  122. elif height > height_standard:
  123. image_np = cv2.resize(image_np, (width_new, height_standard))
  124. cv2.imwrite(image_path, image_np)
  125. # print("resize_image", image_np.shape)
  126. return
  127. except Exception as e:
  128. log("resize_image")
  129. print("resize_image", e, global_type)
  130. return
  131. def remove_red_seal(image_np):
  132. """
  133. 去除红色印章
  134. """
  135. # 获得红色通道
  136. blue_c, green_c, red_c = cv2.split(image_np)
  137. # 多传入一个参数cv2.THRESH_OTSU,并且把阈值thresh设为0,算法会找到最优阈值
  138. thresh, ret = cv2.threshold(red_c, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
  139. # print("remove_red_seal thresh", thresh)
  140. # 实测调整为95%效果好一些
  141. filter_condition = int(thresh * 0.98)
  142. thresh1, red_thresh = cv2.threshold(red_c, filter_condition, 255, cv2.THRESH_BINARY)
  143. # 把图片转回 3 通道
  144. image_and = np.expand_dims(red_thresh, axis=2)
  145. image_and = np.concatenate((image_and, image_and, image_and), axis=-1)
  146. # print(image_and.shape)
  147. # 膨胀
  148. gray = cv2.cvtColor(image_and, cv2.COLOR_RGB2GRAY)
  149. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
  150. erode = cv2.erode(gray, kernel)
  151. cv2.imshow("erode", erode)
  152. cv2.waitKey(0)
  153. image_and = np.bitwise_and(cv2.bitwise_not(blue_c), cv2.bitwise_not(erode))
  154. result_img = cv2.bitwise_not(image_and)
  155. cv2.imshow("remove_red_seal", result_img)
  156. cv2.waitKey(0)
  157. return result_img
  158. def remove_underline(image_np):
  159. """
  160. 去除文字下划线
  161. """
  162. # 灰度化
  163. gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
  164. # 二值化
  165. binary = cv2.adaptiveThreshold(~gray, 255,
  166. cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,
  167. 15, 10)
  168. # Sobel
  169. kernel_row = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], np.float32)
  170. kernel_col = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], np.float32)
  171. # binary = cv2.filter2D(binary, -1, kernel=kernel)
  172. binary_row = cv2.filter2D(binary, -1, kernel=kernel_row)
  173. binary_col = cv2.filter2D(binary, -1, kernel=kernel_col)
  174. cv2.imshow("custom_blur_demo", binary)
  175. cv2.waitKey(0)
  176. rows, cols = binary.shape
  177. # 识别横线
  178. scale = 5
  179. kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (cols // scale, 1))
  180. erodedcol = cv2.erode(binary_row, kernel, iterations=1)
  181. cv2.imshow("Eroded Image", erodedcol)
  182. cv2.waitKey(0)
  183. dilatedcol = cv2.dilate(erodedcol, kernel, iterations=1)
  184. cv2.imshow("dilate Image", dilatedcol)
  185. cv2.waitKey(0)
  186. return
  187. def getMDFFromFile(path):
  188. _length = 0
  189. try:
  190. _md5 = hashlib.md5()
  191. with open(path, "rb") as ff:
  192. while True:
  193. data = ff.read(4096)
  194. if not data:
  195. break
  196. _length += len(data)
  197. _md5.update(data)
  198. return _md5.hexdigest(), _length
  199. except Exception as e:
  200. traceback.print_exc()
  201. return None, _length
  202. def add_html_format(text_list):
  203. new_text_list = []
  204. for t in text_list:
  205. html_t = "<!DOCTYPE HTML>\n"
  206. html_t += '<head><meta charset="UTF-8"></head>\n'
  207. html_t += "<body>\n"
  208. html_t += t
  209. html_t += "\n</body>\n"
  210. new_text_list.append(html_t)
  211. return new_text_list
  212. if get_platform() == "Windows":
  213. globals().update({"time_out": 1000})
  214. else:
  215. globals().update({"time_out": 300})
  216. # @timeout_decorator.timeout(100, timeout_exception=TimeoutError)
  217. # @timeout(globals().get("time_out"), timeout_exception=TimeoutError, use_signals=False)
  218. def unique_temp_file_process(stream, _type, _md5):
  219. if get_platform() == "Windows":
  220. _global._init()
  221. globals().update({"md5": _md5})
  222. _global.update({"md5": _md5})
  223. log("into unique_temp_file_process")
  224. try:
  225. # 每个调用在temp中创建一个唯一空间
  226. uid1 = uuid.uuid1().hex
  227. unique_space_path = _path + os.sep + "temp" + os.sep + uid1 + os.sep
  228. # unique_space_path = "/mnt/fangjiasheng/" + "temp/" + uid1 + "/"
  229. # 判断冲突
  230. if not os.path.exists(unique_space_path):
  231. if not os.path.exists(_path + os.sep + "temp"):
  232. os.mkdir(_path + os.sep + "temp" + os.sep)
  233. os.mkdir(unique_space_path)
  234. else:
  235. uid2 = uuid.uuid1().hex
  236. if not os.path.exists(_path + os.sep + "temp"):
  237. os.mkdir(_path + os.sep + "temp" + os.sep)
  238. os.mkdir(_path + os.sep + "temp" + os.sep + uid2 + os.sep)
  239. # os.mkdir("/mnt/" + "temp/" + uid2 + "/")
  240. # 在唯一空间中,对传入的文件也保存为唯一
  241. uid3 = uuid.uuid1().hex
  242. file_path = unique_space_path + uid3 + "." + _type
  243. with open(file_path, "wb") as ff:
  244. ff.write(stream)
  245. text = getText(_type, file_path)
  246. # 获取swf转换的图片
  247. swf_images = []
  248. if _type == "swf":
  249. image_name_list = []
  250. for root, dirs, files in os.walk(unique_space_path, topdown=False):
  251. for name in files:
  252. if name[-4:] == ".png" and "resize" not in name:
  253. image_name_list.append(name)
  254. image_name_list.sort(key=lambda x: x)
  255. for name in image_name_list:
  256. with open(os.path.join(unique_space_path, name), "rb") as f:
  257. img_bytes = f.read()
  258. swf_images.append(base64.b64encode(img_bytes))
  259. log("unique_temp_file_process len(swf_images) " + str(len(swf_images)))
  260. return text, swf_images
  261. except TimeoutError:
  262. return [-5], []
  263. except Exception as e:
  264. log("unique_temp_file_process failed!")
  265. traceback.print_exc()
  266. return [-1], []
  267. finally:
  268. print("======================================")
  269. try:
  270. if get_platform() == "Linux":
  271. # log("not delete temp file")
  272. # 删除该唯一空间下所有文件
  273. if os.path.exists(unique_space_path):
  274. shutil.rmtree(unique_space_path)
  275. except Exception as e:
  276. log("Delete Files Failed!")
  277. def cut_str(text_list, only_text_list, max_bytes_length=2000000):
  278. log("into cut_str")
  279. try:
  280. # 计算有格式总字节数
  281. bytes_length = 0
  282. for text in text_list:
  283. bytes_length += len(bytes(text, encoding='utf-8'))
  284. # print("text_list", bytes_length)
  285. # 小于直接返回
  286. if bytes_length < max_bytes_length:
  287. print("return text_list no cut")
  288. return text_list
  289. # 全部文件连接,重新计算无格式字节数
  290. all_text = ""
  291. bytes_length = 0
  292. for text in only_text_list:
  293. bytes_length += len(bytes(text, encoding='utf-8'))
  294. all_text += text
  295. # print("only_text_list", bytes_length)
  296. # 小于直接返回
  297. if bytes_length < max_bytes_length:
  298. print("return only_text_list no cut")
  299. return only_text_list
  300. # 截取字符
  301. all_text = all_text[:int(max_bytes_length/3)]
  302. # print("text bytes ", len(bytes(all_text, encoding='utf-8')))
  303. # print("return only_text_list has cut")
  304. return [all_text]
  305. except Exception as e:
  306. log("cut_str " + str(e))
  307. return ["-1"]
  308. @memory_decorator
  309. def convert(data, ocr_model, otr_model):
  310. """
  311. 接口返回值:
  312. {[str], 1}: 处理成功
  313. {[-1], 0}: 逻辑处理错误
  314. {[-2], 0}: 接口调用错误
  315. {[-3], 1}: 文件格式错误,无法打开
  316. {[-4], 0}: 各类文件调用第三方包读取超时
  317. {[-5], 0}: 整个转换过程超时
  318. {[-6], 0}: 阿里云UDF队列超时
  319. {[-7], 1}: 文件需密码,无法打开
  320. :return: {"result_html": str([]), "result_text":str([]) "is_success": int}
  321. """
  322. # 控制内存
  323. # soft, hard = resource.getrlimit(resource.RLIMIT_AS)
  324. # resource.setrlimit(resource.RLIMIT_AS, (15 * 1024 ** 3, hard))
  325. log("into convert")
  326. start_time = time.time()
  327. _md5 = "1000000"
  328. try:
  329. # 模型加入全局变量
  330. globals().update({"global_ocr_model": ocr_model})
  331. globals().update({"global_otr_model": otr_model})
  332. stream = base64.b64decode(data.get("file"))
  333. _type = data.get("type")
  334. _md5 = get_md5_from_bytes(stream)
  335. if get_platform() == "Windows":
  336. # 解除超时装饰器,直接访问原函数
  337. origin_unique_temp_file_process = unique_temp_file_process.__wrapped__
  338. text, swf_images = origin_unique_temp_file_process(stream, _type, _md5)
  339. else:
  340. # Linux 通过装饰器设置整个转换超时时间
  341. try:
  342. text, swf_images = unique_temp_file_process(stream, _type, _md5)
  343. except TimeoutError:
  344. log("convert time out! 1200 sec")
  345. text = [-5]
  346. swf_images = []
  347. error_code = [[-x] for x in range(1, 9)]
  348. still_success_code = [[-3], [-7]]
  349. if text in error_code:
  350. if text in still_success_code:
  351. print({"failed result": text, "is_success": 1}, time.time() - start_time)
  352. return {"result_html": [str(text[0])], "result_text": [str(text[0])],
  353. "is_success": 1}
  354. else:
  355. print({"failed result": text, "is_success": 0}, time.time() - start_time)
  356. return {"result_html": [str(text[0])], "result_text": [str(text[0])],
  357. "is_success": 0}
  358. # 结果保存result.html
  359. if get_platform() == "Windows":
  360. text_str = ""
  361. for t in text:
  362. text_str += t
  363. to_html("../result.html", text_str)
  364. # 取纯文本
  365. only_text = []
  366. for t in text:
  367. new_t = BeautifulSoup(t, "lxml").get_text()
  368. new_t = re.sub("\n", "", new_t)
  369. only_text.append(new_t)
  370. # 判断长度,过长截取
  371. text = cut_str(text, only_text)
  372. only_text = cut_str(only_text, only_text)
  373. if len(only_text) == 0:
  374. only_text = [""]
  375. if only_text[0] == '' and len(only_text) <= 1:
  376. print({"md5: ": str(_md5), "finished result": ["", 0], "is_success": 1}, time.time() - start_time)
  377. else:
  378. print("md5: " + str(_md5), {"finished result": [str(only_text)[:20], len(str(text))],
  379. "is_success": 1}, time.time() - start_time)
  380. return {"result_html": text, "result_text": only_text, "is_success": 1}
  381. except Exception as e:
  382. print({"md5: ": str(_md5), "failed result": [-1], "is_success": 0}, time.time() - start_time)
  383. print("convert", traceback.print_exc())
  384. return {"result_html": ["-1"], "result_text": ["-1"], "is_success": 0}
  385. # 接口配置
  386. app = Flask(__name__)
  387. @app.route('/convert', methods=['POST'])
  388. def _convert():
  389. """
  390. 接口返回值:
  391. {[str], 1}: 处理成功
  392. {[-1], 0}: 逻辑处理错误
  393. {[-2], 0}: 接口调用错误
  394. {[-3], 1}: 文件格式错误,无法打开
  395. {[-4], 0}: 各类文件调用第三方包读取超时
  396. {[-5], 0}: 整个转换过程超时
  397. {[-6], 0}: 阿里云UDF队列超时
  398. {[-7], 1}: 文件需密码,无法打开
  399. :return: {"result_html": str([]), "result_text":str([]) "is_success": int}
  400. """
  401. # log("growth start" + str(objgraph.growth()))
  402. # log("most_common_types start" + str(objgraph.most_common_types(20)))
  403. # tracemalloc.start(25)
  404. # snapshot = tracemalloc.take_snapshot()
  405. _global._init()
  406. _global.update({"md5": "1"+"0"*15})
  407. set_flask_global()
  408. # _global.update({"port": str(port)})
  409. log("into convert")
  410. start_time = time.time()
  411. _md5 = _global.get("md5")
  412. _type = None
  413. try:
  414. if not request.form:
  415. log("convert no data!")
  416. raise ConnectionError
  417. data = request.form
  418. stream = base64.b64decode(data.get("file"))
  419. _type = data.get("type")
  420. _md5 = get_md5_from_bytes(stream)
  421. _md5 = _md5[0]
  422. _global.update({"md5": _md5})
  423. if get_platform() == "Windows":
  424. # 解除超时装饰器,直接访问原函数
  425. # origin_unique_temp_file_process = unique_temp_file_process.__wrapped__
  426. # text, swf_images = origin_unique_temp_file_process(stream, _type)
  427. try:
  428. text, swf_images = unique_temp_file_process(stream, _type, _md5)
  429. except TimeoutError:
  430. log("convert time out! 300 sec")
  431. text = [-5]
  432. swf_images = []
  433. else:
  434. # Linux 通过装饰器设置整个转换超时时间
  435. try:
  436. text, swf_images = unique_temp_file_process(stream, _type, _md5)
  437. except TimeoutError:
  438. log("convert time out! 300 sec")
  439. text = [-5]
  440. swf_images = []
  441. still_success_code = [-3, -4, -7]
  442. if judge_error_code(text):
  443. if judge_error_code(text, still_success_code):
  444. is_success = 1
  445. else:
  446. is_success = 0
  447. log("md5: " + str(_md5)
  448. + " finished result: " + str(text)
  449. + " is_success: " + str(is_success)
  450. + " " + str(time.time() - start_time))
  451. return json.dumps({"result_html": [str(text[0])], "result_text": [str(text[0])],
  452. "is_success": is_success, "swf_images": str(swf_images)})
  453. # 结果保存result.html
  454. # if get_platform() == "Windows":
  455. text_str = ""
  456. for t in text:
  457. text_str += t
  458. to_html(os.path.dirname(os.path.abspath(__file__)) + "/../result.html", text_str)
  459. # 取纯文本
  460. only_text = []
  461. for t in text:
  462. new_t = BeautifulSoup(t, "lxml").get_text()
  463. new_t = re.sub("\n", "", new_t)
  464. only_text.append(new_t)
  465. # 判断长度,过长截取
  466. text = cut_str(text, only_text)
  467. only_text = cut_str(only_text, only_text)
  468. if len(only_text) == 0:
  469. only_text = [""]
  470. if only_text[0] == '' and len(only_text) <= 1:
  471. print({"finished result": ["", 0], "is_success": 1}, time.time() - start_time)
  472. log("md5: " + str(_md5) + " "
  473. + " finished result: ['', 0] is_success: 1 "
  474. + str(_type) + " "
  475. + str(time.time() - start_time))
  476. else:
  477. log("md5: " + str(_md5) +
  478. " finished result: " + str(only_text)[:20] + " "
  479. + str(len(str(text))) + " is_success: 1 "
  480. + str(_type) + " "
  481. + str(time.time() - start_time))
  482. # log("growth end" + str(objgraph.growth()))
  483. # log("most_common_types end" + str(objgraph.most_common_types(20)))
  484. return json.dumps({"result_html": text, "result_text": only_text,
  485. "is_success": 1, "swf_images": str(swf_images)})
  486. except ConnectionError:
  487. log("convert post has no data!" + " failed result: [-2] is_success: 0 " +
  488. str(time.time() - start_time))
  489. return json.dumps({"result_html": ["-2"], "result_text": ["-2"],
  490. "is_success": 0, "swf_images": str([])})
  491. except Exception as e:
  492. log("md5: " + str(_md5) + " failed result: [-1] is_success: 0 "
  493. + str(_type) + " " +
  494. str(time.time() - start_time))
  495. traceback.print_exc()
  496. return json.dumps({"result_html": ["-1"], "result_text": ["-1"],
  497. "is_success": 0, "swf_images": str([])})
  498. finally:
  499. # _global._del()
  500. # gc.collect()
  501. log("finally")
  502. # snapshot1 = tracemalloc.take_snapshot()
  503. # top_stats = snapshot1.compare_to(snapshot, 'lineno')
  504. # log("[ Top 20 differences ]")
  505. # for stat in top_stats[:20]:
  506. # if stat.size_diff < 0:
  507. # continue
  508. # log(stat)
  509. # gth = objgraph.growth(limit=10)
  510. # for gt in gth:
  511. # log("growth type:%s, count:%s, growth:%s" % (gt[0], gt[1], gt[2]))
  512. # # if gt[2] > 100 or gt[1] > 300:
  513. # # continue
  514. # if gt[2] < 5:
  515. # continue
  516. # _p = os.path.dirname(os.path.abspath(__file__))
  517. # objgraph.show_backrefs(objgraph.by_type(gt[0])[0], max_depth=10, too_many=5,
  518. # filename=_p + "/dots/%s_%s_backrefs.dot" % (_md5, gt[0]))
  519. # objgraph.show_refs(objgraph.by_type(gt[0])[0], max_depth=10, too_many=5,
  520. # filename=_p + "/dots/%s_%s_refs.dot" % (_md5, gt[0]))
  521. # objgraph.show_chain(
  522. # objgraph.find_backref_chain(objgraph.by_type(gt[0])[0], objgraph.is_proper_module),
  523. # filename=_p + "/dots/%s_%s_chain.dot" % (_md5, gt[0])
  524. # )
  525. def test_more(_dir, process_no=None):
  526. file_path_list = []
  527. for root, dirs, files in os.walk(_dir, topdown=False):
  528. for name in files:
  529. file_path_list.append(os.path.join(root, name))
  530. start_time = time.time()
  531. i = 0
  532. for p in file_path_list:
  533. if i % 10 == 0:
  534. if process_no is not None:
  535. print("Process", process_no, i, time.time()-start_time)
  536. else:
  537. print("Loop", i, time.time()-start_time)
  538. test_one(p, from_remote=True)
  539. i += 1
  540. def test_one(p, from_remote=False):
  541. with open(p, "rb") as f:
  542. file_bytes = f.read()
  543. file_base64 = base64.b64encode(file_bytes)
  544. data = {"file": file_base64, "type": p.split(".")[-1], "filemd5": 100}
  545. if from_remote:
  546. ocr_model = None
  547. otr_model = None
  548. _url = 'http://127.0.0.1:15010/convert'
  549. # _url = 'http://192.168.2.102:15010/convert'
  550. # _url = 'http://172.16.160.65:15010/convert'
  551. result = json.loads(request_post(_url, data, time_out=10000))
  552. if p.split(".")[-1] == "swf":
  553. swf_images = eval(result.get("swf_images"))
  554. print(type(swf_images))
  555. # for img in swf_images:
  556. # img_bytes = base64.b64decode(img)
  557. # img = cv2.imdecode(np.frombuffer(img_bytes, np.uint8), cv2.IMREAD_COLOR)
  558. # cv2.imshow("swf_images", img)
  559. # cv2.waitKey(0)
  560. else:
  561. ocr_model = ocr_interface.OcrModels().get_model()
  562. otr_model = otr_interface.OtrModels().get_model()
  563. result = convert(data, ocr_model, otr_model)
  564. print("result_text", result.get("result_text")[0][:20])
  565. print("is_success", result.get("is_success"))
  566. def test_duplicate(path_list, process_no=None):
  567. start_time = time.time()
  568. for i in range(500):
  569. if i % 10 == 0:
  570. if process_no is not None:
  571. print("Process", process_no, i*len(path_list), time.time()-start_time)
  572. else:
  573. print("Loop", i*len(path_list), time.time()-start_time)
  574. for p in path_list:
  575. test_one(p, from_remote=True)
  576. global_type = ""
  577. local_url = "http://127.0.0.1"
  578. if get_platform() == "Windows":
  579. _path = os.path.abspath(os.path.dirname(__file__))
  580. else:
  581. _path = "/home/admin"
  582. if not os.path.exists(_path):
  583. _path = os.path.dirname(os.path.abspath(__file__))
  584. if __name__ == '__main__':
  585. # convert interface
  586. if len(sys.argv) == 2:
  587. port = int(sys.argv[1])
  588. else:
  589. port = 15010
  590. globals().update({"md5": "1"+"0"*15})
  591. globals().update({"port": str(port)})
  592. _global._init()
  593. _global.update({"md5": "1"+"0"*15})
  594. _global.update({"port": str(port)})
  595. ip = get_intranet_ip()
  596. log("my ip"+str(ip))
  597. ip_port_dict = get_ip_port()
  598. ip = "http://" + ip
  599. processes = ip_port_dict.get(ip).get("convert_processes")
  600. set_flask_global()
  601. if get_platform() == "Windows":
  602. app.run(host='0.0.0.0', port=port, processes=1, threaded=False, debug=False)
  603. else:
  604. # app.run(host='0.0.0.0', port=port, processes=processes, threaded=False, debug=False)
  605. app.run(port=15011)
  606. # if get_platform() == "Windows":
  607. # # file_path = "C:/Users/Administrator/Desktop/error7.jpg"
  608. # # file_path = "D:/BIDI_DOC/比地_文档/2022/Test_Interface/20210609202634853485.xlsx"
  609. # # file_path = "D:/BIDI_DOC/比地_文档/2022/Test_ODPS/1624325845476.pdf"
  610. # file_path = "C:/Users/Administrator/Downloads/1650967920520.pdf"
  611. # else:
  612. # file_path = "test1.doc"
  613. # test_one(file_path, from_remote=True)
  614. # if get_platform() == "Windows":
  615. # file_dir = "D:/BIDI_DOC/比地_文档/table_images/"
  616. # else:
  617. # file_dir = "../table_images/"
  618. #
  619. # for j in range(10):
  620. # p = Process(target=test_more, args=(file_dir, j, ))
  621. # p.start()
  622. # p.join()
  623. # if get_platform() == "Windows":
  624. # # file_path_list = ["D:/BIDI_DOC/比地_文档/2022/Test_Interface/1623328459080.doc",
  625. # # "D:/BIDI_DOC/比地_文档/2022/Test_Interface/94961e1987d1090e.xls",
  626. # # "D:/BIDI_DOC/比地_文档/2022/Test_Interface/11111111.rar"]
  627. # file_path_list = ["D:/BIDI_DOC/比地_文档/2022/Test_Interface/1623328459080.doc",
  628. # "D:/BIDI_DOC/比地_文档/2022/Test_Interface/94961e1987d1090e.xls"]
  629. # # file_path_list = ["D:/BIDI_DOC/比地_文档/2022/Test_Interface/1623328459080.doc"]
  630. #
  631. # else:
  632. # file_path_list = ["test1.pdf"]
  633. # for j in range(10):
  634. # p = Process(target=test_duplicate, args=(file_path_list, j, ))
  635. # p.start()
  636. # p.join()