convert.py 31 KB

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