convert.py 27 KB

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