structure_main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 structure.final_structure import one_item_structure
  6. from utils.stem_ans_split import get_split_pos
  7. from utils.washutil import *
  8. from structure.three_parse_structure import *
  9. from utils.pic_pos_judge import img_regroup
  10. from structure.paper_text_structure import WordParseStructure
  11. from func_timeout import func_set_timeout
  12. from utils.xuanzuoti2slave import toslave_bef, toslave_aft
  13. paper_types = ["第三种试卷格式:题目与答案分开",
  14. "第二种试卷格式: 不同时含有或都不含有{答案}和{解析}关键字",
  15. "第一种试卷格式:教师用卷,含答案和解析关键字"]
  16. class StructureExporter(WordParseStructure):
  17. """
  18. 基于wordbin出来的html结果进一步做 试卷类型 非模板结构化
  19. """
  20. def img_repl(self, one_dict):
  21. """
  22. 初步拆分题目后,图片信息的替换
  23. :return:
  24. """
  25. imgs = {s: re.findall("<img.*?/>", one_dict[s]) for s in ['stem', 'key', 'parse']}
  26. for k, imgs_seq in imgs.items():
  27. for img in imgs_seq:
  28. img = re.sub("(?<!\s)(w_h|data-latex)=", r" \1=", img)
  29. one_dict[k] = one_dict[k].replace(img, self.subs2src[img])
  30. # if type(self.img_url) == str and self.img_url:
  31. # one_dict[k] = re.sub(r'<img src="files/', '<img src="' + str(self.img_url), str(one_dict[k]))
  32. if "analy" in one_dict:
  33. for img in re.findall("<img.*?/>", one_dict["analy"]):
  34. img = re.sub("(?<!\s)(w_h|data-latex)=", r" \1=", img)
  35. one_dict["analy"] = one_dict["analy"].replace(img, self.subs2src[img])
  36. return one_dict
  37. # @func_set_timeout(30)
  38. def export(self):
  39. """结构化入口"""
  40. if not self.row_list:
  41. return {"errcode": 1, "errmsgs": "题文没有有效信息", "data": {}}, ""
  42. # 判断考试类型
  43. # paper_other_info = get_exam_type(row_list)
  44. # 第二步:寻找题目和答案的切分点,一定要有“答案”关键字
  45. split_res = get_split_pos(self.row_list)
  46. if type(split_res) == str:
  47. return {"errcode": 1, "errmsgs": split_res, "data": {}}, paper_types[0]
  48. row_list, items_list, ans_list, is_may_ans = split_res
  49. rd2_is_fail = 0
  50. rd1_may_fail = 0
  51. item_res, paper_type, item_no_type = "", "", 1
  52. item_groups, ans_groups = {}, {}
  53. if "【答案】" in "".join(items_list) or "【解析】" in "".join(items_list):
  54. rd1_may_fail = 1
  55. else:
  56. if items_list:
  57. paper_type = paper_types[0]
  58. reform_res = items_ans_reform(items_list, ans_list, self.subject)
  59. if type(reform_res) == str:
  60. return {"errcode": 1, "errmsgs": reform_res, "data": {}}, paper_type
  61. else:
  62. if len(reform_res) == 2:
  63. item_res, item_no_type = reform_res
  64. else:
  65. item_res, item_no_type, rd2_is_fail, item_groups = reform_res
  66. if not items_list or rd1_may_fail or (is_may_ans and rd2_is_fail):
  67. ans_n = re.findall("【答案】", "\n".join(row_list))
  68. parse_n = len(re.findall("【解析】", "\n".join(row_list)))
  69. if self.subject != "地理" and ans_n and len(ans_n) == parse_n > 10: # 带相同个数的答案和解析
  70. paper_type = paper_types[2]
  71. item_res = split_by_keywords(row_list)
  72. if type(item_res) == str and re.search("格式有误|没有换行|题型不明确|题型行格式有问题", item_res):
  73. print("第一种试卷格式解析格式有误")
  74. try:
  75. paper_type = paper_types[1]
  76. item_res = split_by_topicno(row_list, self.subject)
  77. except:
  78. return {"errcode": 1, "errmsgs": item_res, "data": {}}, paper_type
  79. else:
  80. paper_type = paper_types[1]
  81. item_res = split_by_topicno(row_list, self.subject)
  82. item_list =[]
  83. if type(item_res) == str:
  84. return {"errcode": 1, "errmsgs": item_res, "data": {}}, paper_type
  85. else:
  86. if type(item_res) == tuple:
  87. if len(item_res) == 2:
  88. item_list, item_no_type = item_res
  89. else:
  90. item_list, item_no_type, item_groups, ans_groups = item_res
  91. # pprint(item_list)
  92. print('****************初步切分题目的个数*****************', len(item_list))
  93. res = []
  94. if item_list:
  95. item_list = img_regroup(item_list, row_list) # 图片重组判断
  96. if self.subs2src:
  97. item_list = list(map(self.img_repl, item_list)) # 图片信息替换还原
  98. # ---------初步拆分题目错误判断--------------------
  99. # ---------新题型进一步拆分--------------------
  100. new_item = [[k, i] for k, i in enumerate(item_list) if re.search("选[修学]", i["stem"][:10])]
  101. have_slave = 0
  102. to_slave = []
  103. if new_item:
  104. try:
  105. have_slave = 1
  106. for one in new_item:
  107. new_res = toslave_bef(one[1])
  108. if type(new_res) == list:
  109. to_slave.extend(new_res)
  110. item_list.remove(one[1])
  111. else:
  112. item_list[one[0]] = new_res
  113. except:
  114. pass
  115. if to_slave:
  116. item_list.extend(to_slave)
  117. # ==========小题结构化========
  118. # from multiprocessing.dummy import Pool as ThreadPool
  119. # pool = ThreadPool(2) # 比# pool = multiprocessing.Pool(3)速度快
  120. consumer = ['noslave'] * len(item_list)
  121. items_no_type = [item_no_type] * len(item_list)
  122. xyz = zip(item_list, consumer, items_no_type)
  123. # res = list(pool.map(one_item_structure, xyz))
  124. res = list(map(one_item_structure, xyz)) # 和多进程相比,这样速度也很快
  125. # ==========最后的清洗=========
  126. res = wash_after(res, item_groups, ans_groups)
  127. if have_slave and not to_slave:
  128. res = list(map(toslave_aft, res))
  129. # 结果返回
  130. if self.is_reparse:
  131. return {"html":self.new_html, "items": res}, paper_type
  132. else:
  133. return {"items": res}, paper_type
  134. @staticmethod
  135. def _get_all_errors(res):
  136. """
  137. 整套试卷结构化完成以后,把所有报错放在一个list里面:
  138. all_errors = [{"单选题第1题目":[]},{"解答题第2题":[]},{},{}]
  139. :param res:
  140. :return:
  141. """
  142. type_names = []
  143. errmgs = []
  144. spliterr_point = []
  145. for one_res in res:
  146. type_names.append(one_res["type"])
  147. if "text_errmsgs" in one_res:
  148. errmgs.append(one_res["text_errmsgs"])
  149. else:
  150. errmgs.append("")
  151. if 'spliterr_point' in one_res:
  152. spliterr_point.append(one_res['spliterr_point'])
  153. # 给同种题型的名字重新编码
  154. new_names = []
  155. for k, v in enumerate(type_names):
  156. if v:
  157. nums = str(type_names[:k]).count(v)
  158. else:
  159. nums = k
  160. if spliterr_point:
  161. add_n = insert_sort2get_idx(spliterr_point, k+1)
  162. new_names.append("{}第{}题(在整份word中的序号为{}题)".format(v, nums + 1 + add_n, k + 1 + add_n))
  163. else:
  164. new_names.append("{}第{}题(在整份word中的序号为{}题)".format(v, nums + 1, k + 1))
  165. all_errors = []
  166. for name, error in zip(new_names, errmgs):
  167. if len(error) > 0:
  168. all_errors.append({name: error})
  169. return all_errors
  170. if __name__ == '__main__':
  171. # 单份试卷测试
  172. import json
  173. from bson.objectid import ObjectId
  174. # path1 = r"F:\zwj\parse_2021\data\fail\2\2.txt"
  175. # path = r"F:\zwj\parse_2021\res_folder\13.html"
  176. # images_url1 = "" # "http://49.233.23.58:11086/ser_static/4439/files/"
  177. # html = "<p>"+"</p>\n<p>".join(html.split("\n"))+"</p>"
  178. # with open(r"F:\zwj\Text_Structure\fail_files3\c5e222c5fbded2a2264ae002907fc92c__2021_04_16_18_43_23.json", 'r') as load_f:
  179. # html = json.load(load_f)
  180. # print(load_dict)
  181. path2 = r"F:\zwj\new_word_text_extract_2021\data\地理\3\安徽高三地理.html"
  182. # path2 = r"F:\zwj\new_word_text_extract_2021\data\地理\2\2020-2021学年广东省揭阳市揭西县五校九年级(下)第二次联考地理试卷-普通用卷.html"
  183. # path2 = r"F:\zwj\new_word_parse_2021\data\huaxue\huexue2.html"
  184. # path2 = r"F:\zwj\new_word_text_extract_2021\data\phy_clean.html"
  185. html = open(path2, "r", encoding="utf-8").read()
  186. # print(html)
  187. res1 = StructureExporter(html, "",1, "地理").export()
  188. # new_fpath = os.path.join(r"F:\zwj\Text_Structure\fail_files", "res1.html")
  189. # re_f = open(new_fpath, 'a+', encoding='utf-8')
  190. # for i in res1[0]["items"]:
  191. # re_f.write(str(i))
  192. pprint(res1[0]["items"])
  193. print('题目数量:', len(res1[0]["items"]))
  194. # new_fpath = r"F:\zwj\Text_Structure\new_tiku_structure_2021\res_folder\10-28.json"
  195. # re_f = open(new_fpath, 'w', encoding='utf-8')
  196. # json.dump(res1, re_f, ensure_ascii=False)
  197. # mongo = Mongo()
  198. # data = mongo.get_data_info({"_id": ObjectId("5fc64c9c4994183dda7e75b2")})
  199. # # pprint(data["item_ocr"])
  200. # res1 = WordParseStructure(data["item_ocr"], images_url1).structure()
  201. # print(res1)
  202. # print('题目数量:', len(res1[0]["items"]))
  203. # 6837 序号有些乱 6836 图片位置和格式有问题
  204. # 6822 16A、和16B、类型的序号怎么处理 'item_id'有int和 str 型,须统一处理下
  205. # 6820 答案页没有明显标识
  206. # 14.html 只有答案,没有题干
  207. # 21.html 多套题目在一起,多个从1开始的序号,最后一道题,把后面题目都放在一起了,需要判断一下吗?
  208. # import json
  209. # re_f = open("207.txt", 'w', encoding='utf-8')
  210. # json.dump(res1[0], re_f)
  211. # json文件
  212. # for file in os.listdir(r"F:\zwj\Text_Structure\fail_files"):
  213. # path1 = os.path.join(r"F:\zwj\Text_Structure\fail_files", file)
  214. # # path1 = r"F:\zwj\Text_Structure\fail_files\89a6911f57bf89aba898651b27d2a2fc__2021_04_09_18_50_19.json"
  215. # with open(path1,'r',encoding='utf-8') as f:
  216. # html= json.load(f)
  217. # pprint(html)
  218. # # try:
  219. # # res1 = WordParseStructure(html, "").structure()
  220. # # os.remove(path1)
  221. # # except:
  222. # # pass
  223. # res1 = WordParseStructure(html, "").structure()
  224. # pprint(res1)
  225. # print('题目数量:', len(res1[0]["items"]))