structure_main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/env/python
  2. # -*- coding:utf-8 -*-
  3. from pprint import pprint
  4. # from utils.exam_type import get_exam_type
  5. # from utils.get_data import Mongo
  6. from structure.final_structure import one_item_structure
  7. from utils.stem_ans_split import get_split_pos
  8. from utils.washutil import *
  9. from structure.three_parse_structure import *
  10. from utils.pic_pos_judge import img_regroup
  11. from func_timeout import func_set_timeout
  12. from utils.xuanzuoti2slave import toslave_bef, toslave_aft
  13. paper_types = ["第三种试卷格式:题目与答案分开",
  14. "第二种试卷格式: 不同时含有或都不含有{答案}和{解析}关键字",
  15. "第一种试卷格式:教师用卷,含答案和解析关键字"]
  16. class WordParseStructure:
  17. """
  18. 基于wordbin出来的html结果进一步做 试卷类型 非模板结构化
  19. """
  20. def __init__(self, html, wordid, is_reparse=0, must_latex=0):
  21. self.html = html
  22. self.is_reparse = is_reparse
  23. self.wordid = wordid
  24. self.must_latex = must_latex
  25. def img_repl(self, one_dict):
  26. """
  27. 初步拆分题目后,图片信息的替换
  28. :return:
  29. """
  30. imgs = {s: re.findall("<img.*?/>", one_dict[s]) for s in ['stem', 'key', 'parse']}
  31. for k, imgs_seq in imgs.items():
  32. for img in imgs_seq:
  33. img = re.sub("(?<!\s)(w_h|data-latex)=", r" \1=", img)
  34. if img in self.subs2src:
  35. one_dict[k] = one_dict[k].replace(img, self.subs2src[img])
  36. # if type(self.img_url) == str and self.img_url:
  37. # one_dict[k] = re.sub(r'<img src="files/', '<img src="' + str(self.img_url), str(one_dict[k]))
  38. if "analy" in one_dict:
  39. for img in re.findall("<img.*?/>", one_dict["analy"]):
  40. img = re.sub("(?<!\s)(w_h|data-latex)=", r" \1=", img)
  41. one_dict["analy"] = one_dict["analy"].replace(img, self.subs2src[img])
  42. return one_dict
  43. # @func_set_timeout(30)
  44. def structure(self):
  45. """结构化入口"""
  46. # 第一步:清洗
  47. row_list, self.subs2src, new_html = HtmlWash(self.html, self.wordid, self.is_reparse,
  48. must_latex=self.must_latex).html_cleal()
  49. # pprint(row_list)
  50. if not row_list:
  51. return {"errcode": 1, "errmsgs": "题文没有有效信息", "data": {}}, ""
  52. # 判断考试类型
  53. # paper_other_info = get_exam_type(row_list)
  54. # 第二步:寻找题目和答案的切分点,一定要有“答案”关键字
  55. split_res = get_split_pos(row_list)
  56. if type(split_res) == str:
  57. return {"errcode": 1, "errmsgs": split_res, "data": {}}, paper_types[0]
  58. row_list, items_list, ans_list, is_may_ans = split_res
  59. rd2_is_fail = 0
  60. rd1_may_fail = 0
  61. item_res, paper_type, item_no_type = "", "", 1
  62. if "【答案】" in "".join(items_list) or "【解析】" in "".join(items_list):
  63. rd1_may_fail = 1
  64. else:
  65. if items_list:
  66. paper_type = paper_types[0]
  67. reform_res = items_ans_reform(items_list, ans_list)
  68. if type(reform_res) == str:
  69. return {"errcode": 1, "errmsgs": reform_res, "data": {}}, paper_type
  70. else:
  71. if len(reform_res)==2:
  72. item_res = reform_res
  73. else:
  74. item_res, item_no_type, rd2_is_fail= reform_res
  75. if not items_list or rd1_may_fail or (is_may_ans and rd2_is_fail):
  76. ans_n = re.findall("【答案】", "\n".join(row_list))
  77. if ans_n and len(ans_n) == len(re.findall("【解析】", "\n".join(row_list))) > 10: # 带相同个数的答案和解析
  78. paper_type = paper_types[2]
  79. item_res = split_by_keywords(row_list)
  80. if type(item_res) == str and re.search("格式有误|没有换行|题型不明确|题型行格式有问题", item_res):
  81. print("第一种试卷格式解析格式有误")
  82. try:
  83. paper_type = paper_types[1]
  84. item_res = split_by_topicno(row_list)
  85. except:
  86. return {"errcode": 1, "errmsgs": item_res, "data": {}}, paper_type
  87. else:
  88. paper_type = paper_types[1]
  89. item_res = split_by_topicno(row_list)
  90. if type(item_res) == str:
  91. return {"errcode": 1, "errmsgs": item_res, "data": {}}, paper_type
  92. else:
  93. item_list = item_res
  94. if type(item_res) == tuple:
  95. item_list, item_no_type = item_res
  96. # pprint(item_list)
  97. print('****************初步切分题目的个数*****************', len(item_list))
  98. res = []
  99. if item_list:
  100. item_list = img_regroup(item_list, row_list) # 图片重组判断
  101. if self.subs2src:
  102. item_list = list(map(self.img_repl, item_list)) # 图片信息替换还原
  103. # ---------初步拆分题目错误判断--------------------
  104. # ---------新题型进一步拆分--------------------
  105. # new_item = [[k, i] for k, i in enumerate(item_list) if re.search("选[修学考]", i["stem"][:10])]
  106. # have_slave = 0
  107. # to_slave = {}
  108. # if new_item:
  109. # try:
  110. # have_slave = 1
  111. # for one in new_item:
  112. # new_res = toslave_bef(one[1])
  113. # item_list[one[0]] = new_res
  114. # if type(new_res) == list:
  115. # to_slave[one[0]] = new_res
  116. # except:
  117. # pass
  118. # if to_slave:
  119. # item_list = [i if type(i) == list else [i] for i in item_list]
  120. # item_list = sum(item_list, [])
  121. # ==========小题结构化========
  122. # from multiprocessing.dummy import Pool as ThreadPool
  123. # pool = ThreadPool(2) # 比# pool = multiprocessing.Pool(3)速度快
  124. consumer = ['toslave'] * len(item_list)
  125. items_no_type = [item_no_type] * len(item_list)
  126. xyz = zip(item_list, consumer, items_no_type)
  127. # res = list(pool.map(one_item_structure, xyz))
  128. res = list(map(one_item_structure, xyz)) # 和多进程相比,这样速度也很快
  129. # pprint(res)
  130. # ==========最后的清洗=========
  131. res = wash_after(res)
  132. # if have_slave and not to_slave:
  133. # res = list(map(toslave_aft, res))
  134. # 结果返回
  135. if self.is_reparse:
  136. return {"html":new_html, "items": res}, paper_type
  137. else:
  138. return {"items": res}, paper_type
  139. @staticmethod
  140. def _get_all_errors(res):
  141. """
  142. 整套试卷结构化完成以后,把所有报错放在一个list里面:
  143. all_errors = [{"单选题第1题目":[]},{"解答题第2题":[]},{},{}]
  144. :param res:
  145. :return:
  146. """
  147. type_names = []
  148. errmgs = []
  149. spliterr_point = []
  150. for one_res in res:
  151. type_names.append(one_res["type"])
  152. if "text_errmsgs" in one_res:
  153. errmgs.append(one_res["text_errmsgs"])
  154. else:
  155. errmgs.append("")
  156. if 'spliterr_point' in one_res:
  157. spliterr_point.append(one_res['spliterr_point'])
  158. # 给同种题型的名字重新编码
  159. new_names = []
  160. for k, v in enumerate(type_names):
  161. if v:
  162. nums = str(type_names[:k]).count(v)
  163. else:
  164. nums = k
  165. if spliterr_point:
  166. add_n = insert_sort2get_idx(spliterr_point, k+1)
  167. new_names.append("{}第{}题(在整份word中的序号为{}题)".format(v, nums + 1 + add_n, k + 1 + add_n))
  168. else:
  169. new_names.append("{}第{}题(在整份word中的序号为{}题)".format(v, nums + 1, k + 1))
  170. all_errors = []
  171. for name, error in zip(new_names, errmgs):
  172. if len(error) > 0:
  173. all_errors.append({name: error})
  174. return all_errors
  175. if __name__ == '__main__':
  176. # 单份试卷测试
  177. import json
  178. from bson.objectid import ObjectId
  179. # path1 = r"F:\zwj\parse_2021\data\fail\2\2.txt"
  180. # path = r"F:\zwj\parse_2021\res_folder\13.html"
  181. # images_url1 = "" # "http://49.233.23.58:11086/ser_static/4439/files/"
  182. # html = "<p>"+"</p>\n<p>".join(html.split("\n"))+"</p>"
  183. # with open(r"F:\zwj\Text_Structure\fail_files3\c5e222c5fbded2a2264ae002907fc92c__2021_04_16_18_43_23.json", 'r') as load_f:
  184. # html = json.load(load_f)
  185. # print(load_dict)
  186. path2 = r"F:\zwj\Text_Structure\accept_files\64994dc4a3693ef35281fbc5.html"
  187. # path2 = r"C:\Users\Python\Desktop\bug\6419746d11a1cdad550f5502.html"
  188. # path2 = r"F:\zwj\Text_Structure\new_tiku_structure_v3_sci\data\620bbf7aa7d375f4518b98e1.html"
  189. # path2 = r"F:\zwj\new_word_text_extract_v2\data\地理\2\2020-2021学年广东省揭阳市揭西县五校九年级(下)第二次联考地理试卷-普通用卷.html"
  190. # path2 = r"F:\zwj\new_word_parse_2021\data\huaxue\huexue2.html"
  191. # path2 = r"C:\Users\Python\Desktop\bug\6258cc7af84c0e279ac64301.html" # 正则卡死
  192. # path2 = r"C:\Users\Python\Desktop\bug\629073b9f84c0e279ac64811.html" # 正则卡死
  193. # 62650d5cf84c0e279ac643f1 6258cc7af84c0e279ac64301 62660fa2f84c0e279ac643f5
  194. html = open(path2, "r", encoding="utf-8").read()
  195. # html = """
  196. # <html><head><meta charset="utf-8" /></head><body>\n<p>1.下列化学符号中的数字“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示的意义不正确的是</p>\n<p>A.<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image2.png" width="21px" height="24px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示两个氧原子</p>\n<p>B.<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image3.png" width="34px" height="24px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示一个二氧化氮分子含有两个氧原子</p>\n<p>C.<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image4.png" width="40px" height="21px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示两个氢氧根离子</p>\n<p>D.<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image5.png" width="36px" height="28px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image6.png" width="21px" height="17px" data-latex="$$" />”表示氧化镁中镁元素的化合价为<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image6.png" width="21px" height="17px" data-latex="$$" />价</p>\n<p>【答案】</p>\n<p>A</p>\n<p>【解析】</p>\n<p>根据元素符号前面的数字表示原子的个数,元素符号右下角的数字表示一个分子中的原子个数,离子符号前面的数字表示离子的个数,元素符号正上方的数字表示元素的化合价。A.<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image2.png" width="21px" height="24px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示一个氧分子由两个氧原子组成,故选项表示的意义不正确;B.元素符号右下角的数字表示一个分子中的原子个数,故<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image3.png" width="34px" height="24px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示一个二氧化氮分子含有两个氧原子,故表示的意义正确;C.离子符号前面的数字表示离子的个数,故<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image4.png" width="40px" height="21px" data-latex="$$" />:“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示两个氢氧根离子,故表示的意义正确;D.元素符号正上方的数字表示元素的化合价,故<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image7.png" width="36px" height="28px" data-latex="$$" />中的“<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image1.png" width="13px" height="17px" data-latex="$$" />”表示镁元素的化合价为<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image6.png" width="21px" height="17px" data-latex="$$" />价,故表示的意义正确。故选:A。</p>\n<p> </p>\n<p>2.亚油酸具有降低人体血液中胆固醇及血脂的作用,它的化学式为<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image8.png" width="64px" height="24px" data-latex="$$" />,下列说法中正确的是</p>\n<p>A.亚油酸是由三个元素构成的化合物</p>\n<p>B.每个亚油酸分子中含有<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image9.png" width="20px" height="18px" data-latex="$$" />个原子</p>\n<p>C.亚油酸中碳.氧元素的质量比为<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image10.png" width="38px" height="18px" data-latex="$$" /></p>\n<p>D.每个亚油酸分子中含有<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image11.png" width="18px" height="18px" data-latex="$$" />个碳原子、<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image12.png" width="20px" height="18px" data-latex="$$" />个氢原子、<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image13.png" width="9px" height="17px" data-latex="$$" />个氧分子</p>\n<p>【答案】</p>\n<p>C</p>\n<p>【解析】</p>\n<p>A.由化学式可知,亚油酸是由<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image14.png" width="16px" height="18px" data-latex="$$" />、<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image15.png" width="17px" height="17px" data-latex="$$" />、<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image16.png" width="16px" height="18px" data-latex="$$" />三种元素组成的化合物,A错误。B.每个亚油酸分子中含有<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image17.png" width="102px" height="18px" data-latex="$$" />个原子,B错误。C.亚油酸中碳.氧元素的质量比为<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image18.png" width="184px" height="18px" data-latex="$$" />,C正确。D.每个亚油酸分子中含有<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image11.png" width="18px" height="18px" data-latex="$$" />个碳原子、<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image12.png" width="20px" height="18px" data-latex="$$" />个氢原子、<img src="http://192.168.1.140:8800/ser_static/1638177060408824/word/media/image19.png" width="13px" height="17px" data-latex="$$" />个氧原子,D错误。故选:C。</p>\n</body></html>
  197. # """
  198. # print(html)
  199. res1 = WordParseStructure(html, "", 1).structure()
  200. # new_fpath = os.path.join(r"F:\zwj\Text_Structure\fail_files", "res1.html")
  201. # re_f = open(new_fpath, 'a+', encoding='utf-8')
  202. # for i in res1[0]["items"]:
  203. # re_f.write(str(i))
  204. # pprint(res1)
  205. # pprint(res1[0]['items'])
  206. print('题目数量:', len(res1[0]["items"]))
  207. # new_fpath = r"F:\zwj\Text_Structure\new_tiku_structure_2021\res_folder\10-28.json"
  208. # re_f = open(new_fpath, 'w', encoding='utf-8')
  209. # json.dump(res1, re_f, ensure_ascii=False)
  210. # mongo = Mongo()
  211. # data = mongo.get_data_info({"_id": ObjectId("5fc64c9c4994183dda7e75b2")})
  212. # # pprint(data["item_ocr"])
  213. # res1 = WordParseStructure(data["item_ocr"], images_url1).structure()
  214. # print(res1)
  215. # print('题目数量:', len(res1[0]["items"]))
  216. # 6837 序号有些乱 6836 图片位置和格式有问题
  217. # 6822 16A、和16B、类型的序号怎么处理 'item_id'有int和 str 型,须统一处理下
  218. # 6820 答案页没有明显标识
  219. # 14.html 只有答案,没有题干
  220. # 21.html 多套题目在一起,多个从1开始的序号,最后一道题,把后面题目都放在一起了,需要判断一下吗?
  221. # import json
  222. # re_f = open("207.txt", 'w', encoding='utf-8')
  223. # json.dump(res1[0], re_f)
  224. # json文件
  225. # for file in os.listdir(r"F:\zwj\Text_Structure\fail_files"):
  226. # path1 = os.path.join(r"F:\zwj\Text_Structure\fail_files", file)
  227. # # path1 = r"F:\zwj\Text_Structure\fail_files\89a6911f57bf89aba898651b27d2a2fc__2021_04_09_18_50_19.json"
  228. # with open(path1,'r',encoding='utf-8') as f:
  229. # html= json.load(f)
  230. # pprint(html)
  231. # # try:
  232. # # res1 = WordParseStructure(html, "").structure()
  233. # # os.remove(path1)
  234. # # except:
  235. # # pass
  236. # res1 = WordParseStructure(html, "").structure()
  237. # pprint(res1)
  238. # print('题目数量:', len(res1[0]["items"]))