server_phy2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. import logging
  4. from flask import Flask, render_template
  5. from flask import request, redirect, Response
  6. from flask_cors import *
  7. from multiprocessing import Process, Queue
  8. from server_tools import *
  9. from six.moves import urllib
  10. logger = logging.getLogger(__name__)
  11. logger.setLevel(level=logging.INFO)
  12. log_file = os.path.join(r'./logs', 'parse_log.txt') # 日志地址
  13. handler = logging.FileHandler(log_file, mode='a', encoding='utf-8', delay=True)
  14. handler.setLevel(logging.INFO)
  15. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  16. handler.setFormatter(formatter)
  17. # console = logging.StreamHandler()
  18. # console.setLevel(logging.INFO)
  19. # console.setFormatter(formatter)
  20. logger.addHandler(handler)
  21. # logger.addHandler(console)
  22. app = Flask(__name__)
  23. app.debug = True
  24. CORS(app, supports_credentials=True)
  25. '''
  26. errcode=0成功
  27. errcode=1失败
  28. errmsg是具体的失败消息
  29. '''
  30. # 定义上传路径
  31. UPLOAD_FOLDER = r'D:\zwj\word_uploads' # wordbin服务生成文件路径
  32. if not os.path.isdir(UPLOAD_FOLDER):
  33. os.makedirs(UPLOAD_FOLDER)
  34. # --------------------------------------------------------------
  35. @app.route('/')
  36. def index():
  37. return redirect("/all_subject_parse")
  38. # 文件上传的HTML模板,这里没有额外去写html模板了,直接写在这里,方便点吧
  39. @app.route('/all_subject_parse')
  40. def upload():
  41. return '''
  42. <html>
  43. <head>
  44. </head>
  45. <body>
  46. <h1>欢迎使用全学科试题word解析</h1>
  47. <form action="/all_subject_parse" method="post" enctype="multipart/form-data">
  48. <input type="file" name="mydata" />
  49. <input type="submit" value="Upload" />
  50. </form>
  51. </body>
  52. </html>
  53. '''
  54. def read(cache):
  55. while True:
  56. filename, filename_root, callback_url, flag, sid = cache.get(True) # 缓存
  57. print("\n+++++++++++++++还有{}缓存解析+++++++++++++++\n".format(cache.qsize() - 1))
  58. print("\n------callback_url===> {} -------\n".format(callback_url))
  59. logger.info('开始解析文件信息:Get filename={}, filename_root={}, callback_url={}, is_cloud ={},sid ={} from queue\n'
  60. .format(filename, filename_root, callback_url, flag, sid))
  61. # 单线程解析
  62. stime1 = time.time()
  63. try:
  64. res, wordbin_time, paper_type, img_upload_time = parse_word(filename, filename_root, flag, sid)
  65. etime1 = time.time()
  66. logger.info("----wordbin服务所占时间:{}".format(wordbin_time))
  67. logger.info("----整个解析所占时间:{}".format(etime1 - stime1))
  68. logger.info("----该份试卷的格式类型:{}".format(paper_type))
  69. if img_upload_time:
  70. logger.info("----图片上传时间:{}".format(img_upload_time))
  71. except:
  72. # print(traceback.print_exc())
  73. print("--------have callback_url,but time out of parse_word-------")
  74. res = {"time_out": 90,
  75. "id": 0,
  76. "errcode": 1,
  77. "errmsgs": "解析超时,若文件太大,请将文件拆开、分两次上传!"}
  78. # "errmsg": "word读取失败。请尝试:\n 1.请将word中图片改为嵌入式,然后上传。\n 2. 请将word题目拆分为多个word上传。\n 3.请将word中内容复制到新word上传。"
  79. print("------------parse is fail---------------")
  80. try:
  81. headers = {'Content-Type': 'application/json', }
  82. # print(json.dumps(res).encode("utf-8"))
  83. # print(res)
  84. r = requests.post(callback_url,
  85. # json=res, # 可以,但是会进行转义
  86. data=json.dumps(res).encode("utf-8"),
  87. headers=headers)
  88. # timeout=10
  89. print("\n------post 回调地址===> {} -------\n".format(r.status_code))
  90. print("\n------post 返回结果===> {} -------\n".format(r.text))
  91. except TimeoutError:
  92. print("回调超时")
  93. except Exception as e:
  94. print(e, "------回调出错")
  95. if "items" in res and res["items"]:
  96. if re.search(r"wid[/=](\d+)/?", str(callback_url)):
  97. upload_id = re.search(r"wid[/=](\d+)/?", str(callback_url)).group(1)
  98. save_fname = save_post_file(res, filename, upload_id) # 保存返回的解析结果
  99. else:
  100. save_fname = save_post_file(res, filename, '0000')
  101. logger.info("\n----{}解析完保存的数据文件名:\n{}\n".format(os.path.basename(filename), save_fname))
  102. # noinspection PyTypeChecker
  103. @app.route('/all_subject_parse', methods=['POST'])
  104. def do_upload():
  105. """
  106. 该接口函数专门用来接收word和参数,并保存到本地,将保存后的数据放入缓存中;
  107. 参数关键字为:mydata,callback_url,is_cloud,sid
  108. # 文件上传,overwrite=True为覆盖原有的文件,是bottle的用法f.raw_filename
  109. # 如果不加这参数,当服务器已存在同名文件时,将返回“IOError: File exists.”错误
  110. :return:
  111. """
  112. img_file_count = 0
  113. if os.listdir(UPLOAD_FOLDER):
  114. img_file_count = max([int(i) for i in os.listdir(UPLOAD_FOLDER)]) + 1
  115. logger.info("==接收文件:request.POST.dict==>{}".format(request.form.to_dict())) # php传过来的文件
  116. print("==request.POST.dict==>{}".format(request.form.to_dict()))
  117. callback_url = request.form.get('callback_url', "")
  118. flag = request.form.get('is_cloud', "0") # word中的图片是否上传ucloud
  119. sid = request.form.get('sid', "0") # 学管端、教师端参数
  120. # word文件接收
  121. # 旧接口:整个word文件传过来,主要应用在云题库端上传
  122. try:
  123. upfile = request.files.get('mydata')
  124. print("\n------接受文件名==> {}-------\n".format(os.path.basename(upfile.filename)))
  125. if os.path.splitext(upfile.filename)[1] not in [".doc", ".docx"]:
  126. return "only accept .doc .docx files"
  127. file_root1 = os.path.join(UPLOAD_FOLDER, str(img_file_count)) # 每份word保存的文件夹路径
  128. if not os.path.isdir(file_root1):
  129. os.makedirs(file_root1)
  130. new_filename = str(img_file_count) + os.path.splitext(upfile.filename)[1]
  131. filename = os.path.join(file_root1, new_filename) # 文件的绝对路径, 不会含有汉字
  132. upfile.save(filename) # 保存到当地
  133. except:
  134. # 新接口:mydata传过来的是文件地址(json格式),需另外下载
  135. # j_data = json.loads(request.json.get('mydata'))
  136. up_para = request.form.get('mydata')
  137. print("up_para:", up_para)
  138. upfile_url = json.loads(up_para)[0]["file_url"] # word文件的绝对路径
  139. print("文件地址:", upfile_url)
  140. print("\n------接受文件名==> {}-------\n".format(os.path.basename(upfile_url)))
  141. if os.path.splitext(upfile_url)[1] not in [".doc", ".docx"]:
  142. return "only accept .doc .docx files"
  143. file_root1 = os.path.join(UPLOAD_FOLDER, str(img_file_count)) # 每份word保存的文件夹路径
  144. if not os.path.isdir(file_root1):
  145. os.makedirs(file_root1)
  146. # 根据url地址下载word文件
  147. new_filename = str(img_file_count) + os.path.splitext(upfile_url)[1]
  148. filename = os.path.join(file_root1, new_filename) # 文件的绝对路径, 不会含有汉字
  149. try:
  150. urllib.request.urlretrieve(upfile_url, filename) # 下载到指定位置
  151. except:
  152. return "word文件下载失败,请重新上传"
  153. print('------word Successfully downloaded-----')
  154. # ----------------------------------------------------------------------
  155. # 开一个进程对filename 进行解析
  156. if callback_url:
  157. cache_file.put([filename, file_root1, callback_url, flag, sid])
  158. print("-----当前缓存还有{}-----".format(int(cache_file.qsize()) - 1))
  159. return json.dumps({"errcode": 0, "errmsg": "OK", "docsbefore": int(cache_file.qsize()) - 1},
  160. ensure_ascii=False).encode("utf-8")
  161. else: # 没有回调地址时,简易网页上传
  162. stime1 = time.time()
  163. try:
  164. res, wordbin_time, paper_type, img_upload_time = parse_word(filename, None)
  165. etime1 = time.time()
  166. print("------------简易接口上传,解析成功---------------")
  167. logger.info("\n------------简易接口上传,解析成功---------------")
  168. logger.info("\n开始解析文件:{}".format(filename))
  169. logger.info("\n----wordbin服务所占时间:{}".format(wordbin_time))
  170. logger.info("\n----整个解析所占时间:{}".format(etime1 - stime1))
  171. logger.info("\n----该份试卷的格式类型:{}".format(paper_type))
  172. except:
  173. print("------------简易接口上传,解析失败---------------")
  174. res = {"time_out": 3,
  175. "errcode": 1,
  176. "errmsg": "word读取失败。请尝试:\n 1.请确定试卷版面格式是否为常见的试卷排版格式,删除不规范格式;\n"
  177. "2.请将word中内容复制到新word上传;\n 3. 请将word题目拆分为多个word上传。\n 4.请检查图片格式,将word中图片改为嵌入式后再上传。"}
  178. if "items" in res and res["items"]:
  179. save_fname = save_post_file(res, filename, '0011')
  180. print("\n----{}解析完保存的数据文件名:\n{}".format(os.path.basename(filename), save_fname))
  181. new_res = []
  182. for r in res["items"]:
  183. dd = [r["item_id"], r["type"], r["stem"],
  184. r["key"], r["analysis"],r["text_errmsgs"]]
  185. if "options" in r:
  186. r["options"] = [chr(65+k)+'、'+ opt for k, opt in enumerate(r["options"])]
  187. dd[2] += "<br/>===================<br/>【选项】<br/>" \
  188. + ";<br/>".join(r["options"]).replace("<br/>;", ";")
  189. new_res.append(dd)
  190. import pandas as pd
  191. resdf = pd.DataFrame(new_res)
  192. resdf.columns = ["题号", "题型", "题干", "答案", "解析","错误信息"]
  193. pd.set_option('display.max_columns', None)
  194. pd.set_option('display.max_rows', None)
  195. pd.set_option('expand_frame_repr', True) # 允许换行
  196. pd.set_option('display.width', -1)
  197. pd.set_option('display.max_colwidth', -1) # 自动最大列宽
  198. # 如何将图片显示出来:图片属性格式要符合前端显示标准
  199. return render_template('res.html',
  200. items=[resdf.to_html(header=True,
  201. index=False,
  202. escape=False,
  203. justify="center")],
  204. res_json=json.dumps(res, ensure_ascii=False)
  205. )
  206. else:
  207. # resp = Response_headers(json.dumps(res, ensure_ascii=False).encode("utf-8")) # , indent=4
  208. save_fname = save_post_file(res, filename, '0011')
  209. print("\n----{}解析完保存的数据文件名:\n{}".format(os.path.basename(filename), save_fname))
  210. resp = json.dumps(res, ensure_ascii=False)
  211. return resp
  212. @app.route('/ser_static/<path:file_path>', methods=["GET"])
  213. def ser_static(file_path): # endpoint的位置是函数接口名,不能用static,与flask内部变量重名
  214. """
  215. 将本地图片供php调用,上传Ucloud时该函数不使用
  216. :param file_path: 图片的本地绝对路径
  217. :return:
  218. """
  219. # filepath = request.args.get('q') # 针对/**/=?类型
  220. file = os.path.join(UPLOAD_FOLDER, file_path)
  221. if "image" in file:
  222. resize_img(file, file)
  223. # resp = Response(base64.b64encode(open(file, 'rb').read()).decode()) # 仍无法显示图片
  224. resp = Response(open(file, 'rb'))
  225. return resp
  226. if __name__ == "__main__":
  227. # 解析文件的队列
  228. cache_file = Queue()
  229. start_word2html_app(kill_mathtype=True)
  230. # 读取解析进程
  231. pr_parse = Process(target=read, args=(cache_file,))
  232. pr_parse.start()
  233. print("parse pid:", pr_parse.pid)
  234. app.run(host="0.0.0.0", port=11088, threaded=True, debug=True)