convert.py 34 KB

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