convert_docx.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. import inspect
  2. import os
  3. import sys
  4. sys.path.append(os.path.dirname(__file__) + "/../")
  5. from format_convert.convert_tree import _Document, _Sentence, _Page, _Image, _Table
  6. import logging
  7. import re
  8. import traceback
  9. import xml
  10. import zipfile
  11. import docx
  12. from format_convert.convert_image import picture2text
  13. from format_convert.utils import judge_error_code, add_div, get_logger, log, memory_decorator
  14. from format_convert.wrapt_timeout_decorator import timeout
  15. @memory_decorator
  16. def docx2text(path, unique_type_dir):
  17. log("into docx2text")
  18. try:
  19. try:
  20. doc = docx.Document(path)
  21. except Exception as e:
  22. print("docx format error!", e)
  23. print(traceback.print_exc())
  24. log("docx format error!")
  25. return [-3]
  26. # 遍历段落
  27. # print("docx2text extract paragraph")
  28. paragraph_text_list = []
  29. for paragraph in doc.paragraphs:
  30. if paragraph.text != "":
  31. paragraph_text_list.append("<div>" + paragraph.text + "</div>" )
  32. # print("paragraph_text", paragraph.text)
  33. # 遍历表
  34. try:
  35. table_text_list = read_xml_table(path, unique_type_dir)
  36. except TimeoutError:
  37. return [-4]
  38. if judge_error_code(table_text_list):
  39. return table_text_list
  40. # 顺序遍历图片
  41. # print("docx2text extract image")
  42. image_text_list = []
  43. temp_image_path = unique_type_dir + "temp_image.png"
  44. pattern = re.compile('rId\d+')
  45. for graph in doc.paragraphs:
  46. for run in graph.runs:
  47. if run.text == '':
  48. try:
  49. if not pattern.search(run.element.xml):
  50. continue
  51. content_id = pattern.search(run.element.xml).group(0)
  52. content_type = doc.part.related_parts[content_id].content_type
  53. except Exception as e:
  54. print("docx no image!", e)
  55. continue
  56. if not content_type.startswith('image'):
  57. continue
  58. # 写入临时文件
  59. img_data = doc.part.related_parts[content_id].blob
  60. with open(temp_image_path, 'wb') as f:
  61. f.write(img_data)
  62. # if get_platform() == "Windows":
  63. # print("img_data", img_data)
  64. if img_data is None:
  65. continue
  66. # 识别图片文字
  67. image_text = picture2text(temp_image_path)
  68. if image_text == [-2]:
  69. return [-2]
  70. if image_text == [-1]:
  71. return [-1]
  72. if image_text == [-3]:
  73. continue
  74. image_text = image_text[0]
  75. image_text_list.append(add_div(image_text))
  76. # 解析document.xml,获取文字顺序
  77. order_list = read_xml_order(path, unique_type_dir)
  78. if order_list == [-2]:
  79. return [-2]
  80. if order_list == [-1]:
  81. return [-1]
  82. text = ""
  83. # print("len(order_list)", len(order_list))
  84. # print("len(paragraph_text_list)", len(paragraph_text_list))
  85. # print("len(image_text_list)", len(image_text_list))
  86. # print("len(table_text_list)", len(table_text_list))
  87. for tag in order_list:
  88. if tag == "w:t":
  89. if len(paragraph_text_list) > 0:
  90. text += paragraph_text_list.pop(0)
  91. if tag == "wp:docPr":
  92. if len(image_text_list) > 0:
  93. text += image_text_list.pop(0)
  94. if tag == "w:tbl":
  95. if len(table_text_list) > 0:
  96. text += table_text_list.pop(0)
  97. return [text]
  98. except Exception as e:
  99. log("docx2text error!")
  100. print("docx2text", traceback.print_exc())
  101. return [-1]
  102. @timeout(50, timeout_exception=TimeoutError)
  103. def read_xml_order(path, save_path):
  104. log("into read_xml_order")
  105. try:
  106. try:
  107. f = zipfile.ZipFile(path)
  108. for file in f.namelist():
  109. if "word/document.xml" == str(file):
  110. f.extract(file, save_path)
  111. f.close()
  112. except Exception as e:
  113. log("docx format error!")
  114. return [-3]
  115. try:
  116. collection = xml_analyze(save_path + "word/document.xml")
  117. except TimeoutError:
  118. log("xml_analyze timeout")
  119. return [-4]
  120. body = collection.getElementsByTagName("w:body")[0]
  121. order_list = []
  122. text_list = []
  123. for line in body.childNodes:
  124. # print(str(line))
  125. if "w:p" in str(line):
  126. text = line.getElementsByTagName("w:t")
  127. picture = line.getElementsByTagName("wp:docPr")
  128. if text:
  129. order_list.append("w:t")
  130. temp_text = ""
  131. for t in text:
  132. if len(t.childNodes) > 0:
  133. temp_text += t.childNodes[0].nodeValue
  134. else:
  135. continue
  136. text_list.append(temp_text)
  137. if picture:
  138. order_list.append("wp:docPr")
  139. for line1 in line.childNodes:
  140. if "w:r" in str(line1):
  141. # print("read_xml_order", "w:r")
  142. picture1 = line1.getElementsByTagName("w:pict")
  143. if picture1:
  144. order_list.append("wp:docPr")
  145. if "w:tbl" in str(line):
  146. order_list.append("w:tbl")
  147. read_xml_table(path, save_path)
  148. return [order_list, text_list]
  149. except Exception as e:
  150. log("read_xml_order error!")
  151. print("read_xml_order", traceback.print_exc())
  152. # log_traceback("read_xml_order")
  153. return [-1]
  154. @timeout(50, timeout_exception=TimeoutError)
  155. def read_xml_table(path, save_path):
  156. log("into read_xml_table")
  157. try:
  158. try:
  159. f = zipfile.ZipFile(path)
  160. for file in f.namelist():
  161. if "word/document.xml" == str(file):
  162. f.extract(file, save_path)
  163. f.close()
  164. except Exception as e:
  165. # print("docx format error!", e)
  166. log("docx format error!")
  167. return [-3]
  168. log("xml_analyze%s"%(save_path))
  169. try:
  170. collection = xml_analyze(save_path + "word/document.xml")
  171. except TimeoutError:
  172. log("xml_analyze timeout")
  173. return [-4]
  174. log("xml_analyze done")
  175. body = collection.getElementsByTagName("w:body")[0]
  176. table_text_list = []
  177. # print("body.childNodes", body.childNodes)
  178. for line in body.childNodes:
  179. if "w:tbl" in str(line):
  180. # print("str(line)", str(line))
  181. table_text = '<table border="1">'
  182. tr_list = line.getElementsByTagName("w:tr")
  183. # print("line.childNodes", line.childNodes)
  184. tr_index = 0
  185. tr_text_list = []
  186. tr_text_list_colspan = []
  187. for tr in tr_list:
  188. table_text = table_text + "<tr>"
  189. tc_list = tr.getElementsByTagName("w:tc")
  190. tc_index = 0
  191. tc_text_list = []
  192. for tc in tc_list:
  193. tc_text = ""
  194. # 获取一格占多少列
  195. col_span = tc.getElementsByTagName("w:gridSpan")
  196. if col_span:
  197. col_span = int(col_span[0].getAttribute("w:val"))
  198. else:
  199. col_span = 1
  200. # 获取是否是合并单元格的下一个空单元格
  201. is_merge = tc.getElementsByTagName("w:vMerge")
  202. if is_merge:
  203. is_merge = is_merge[0].getAttribute("w:val")
  204. if is_merge == "continue":
  205. col_span_index = 0
  206. real_tc_index = 0
  207. # if get_platform() == "Windows":
  208. # print("read_xml_table tr_text_list", tr_text_list)
  209. # print("read_xml_table tr_index", tr_index)
  210. if 0 <= tr_index - 1 < len(tr_text_list):
  211. for tc_colspan in tr_text_list[tr_index - 1]:
  212. if col_span_index < tc_index:
  213. col_span_index += tc_colspan[1]
  214. real_tc_index += 1
  215. # print("tr_index-1, real_tc_index", tr_index-1, real_tc_index)
  216. # print(tr_text_list[tr_index-1])
  217. if real_tc_index < len(tr_text_list[tr_index - 1]):
  218. tc_text = tr_text_list[tr_index - 1][real_tc_index][0]
  219. table_text = table_text + "<td colspan=" + str(col_span) + ">"
  220. p_list = tc.getElementsByTagName("w:p")
  221. for p in p_list:
  222. t = p.getElementsByTagName("w:t")
  223. if t:
  224. for tt in t:
  225. # print("tt", tt.childNodes)
  226. if len(tt.childNodes) > 0:
  227. tc_text += tt.childNodes[0].nodeValue
  228. table_text = table_text + tc_text + "</td>"
  229. tc_index += 1
  230. tc_text_list.append([tc_text, col_span])
  231. table_text += "</tr>"
  232. tr_index += 1
  233. tr_text_list.append(tc_text_list)
  234. table_text += "</table>"
  235. table_text_list.append(table_text)
  236. return table_text_list
  237. except Exception as e:
  238. log("read_xml_table error")
  239. print("read_xml_table", traceback.print_exc())
  240. return [-1]
  241. @timeout(25, timeout_exception=TimeoutError)
  242. def xml_analyze(path):
  243. # 解析xml
  244. DOMTree = xml.dom.minidom.parse(path)
  245. collection = DOMTree.documentElement
  246. return collection
  247. def read_docx_table(document):
  248. table_text_list = []
  249. for table in document.tables:
  250. table_text = "<table>"
  251. # print("==================")
  252. for row in table.rows:
  253. table_text += "<tr>"
  254. for cell in row.cells:
  255. table_text += "<td>" + re.sub("\s","",str(cell.text)) + "</td>"
  256. table_text += "</tr>"
  257. table_text += "</table>"
  258. # print(table_text)
  259. table_text_list.append(table_text)
  260. return table_text_list
  261. class DocxConvert:
  262. def __init__(self, path, unique_type_dir):
  263. self._doc = _Document(path)
  264. self.path = path
  265. self.unique_type_dir = unique_type_dir
  266. @memory_decorator
  267. def init_package(self):
  268. # 各个包初始化
  269. try:
  270. self.docx = docx.Document(self.path)
  271. self.zip = zipfile.ZipFile(self.path)
  272. except:
  273. log("cannot open docx!")
  274. traceback.print_exc()
  275. self._doc.error_code = [-3]
  276. def convert(self):
  277. self.init_package()
  278. if self._doc.error_code is not None:
  279. return
  280. order_and_text_list = self.get_orders()
  281. if judge_error_code(order_and_text_list):
  282. self._doc.error_code = order_and_text_list
  283. return
  284. order_list, text_list = order_and_text_list
  285. # test
  286. # for i in range(len(text_list)):
  287. # print(order_list[i], text_list[i])
  288. table_list = self.get_tables()
  289. if judge_error_code(table_list):
  290. self._doc.error_code = table_list
  291. return
  292. # paragraph_list = self.get_paragraphs()
  293. image_list = self.get_images()
  294. self._page = _Page(None, 0)
  295. order_y = 0
  296. doc_pr_cnt = 0
  297. for tag in order_list:
  298. bbox = (0, order_y, 0, 0)
  299. if tag == "w:t":
  300. if len(text_list) > 0:
  301. _para = text_list.pop(0)
  302. _sen = _Sentence(_para, bbox)
  303. _sen.combine=False
  304. self._page.add_child(_sen)
  305. if tag == "wp:docPr":
  306. if len(image_list) > 0:
  307. temp_image_path = self.unique_type_dir + "docpr" + str(doc_pr_cnt) + ".png"
  308. _image = image_list.pop(0)
  309. with open(temp_image_path, "wb") as f:
  310. f.write(_image)
  311. _img = _Image(_image, temp_image_path, bbox)
  312. _img.is_from_docx = True
  313. self._page.add_child(_img)
  314. doc_pr_cnt += 1
  315. if tag == "w:tbl":
  316. if len(table_list) > 0:
  317. _table = table_list.pop(0)
  318. _table = _Table(_table, bbox)
  319. _table.is_html = True
  320. self._page.add_child(_table)
  321. order_y += 1
  322. if self._doc.error_code is None and self._page.error_code is not None:
  323. self._doc.error_code = self._page.error_code
  324. self._doc.add_child(self._page)
  325. def get_paragraphs(self):
  326. # 遍历段落
  327. paragraph_list = []
  328. for paragraph in self.docx.paragraphs:
  329. if paragraph.text != "":
  330. paragraph_list.append(paragraph.text)
  331. return paragraph_list
  332. @memory_decorator
  333. def get_tables(self):
  334. # 遍历表
  335. table_list = read_xml_table(self.path, self.unique_type_dir)
  336. return table_list
  337. def get_images(self):
  338. # 顺序遍历图片
  339. image_list = []
  340. pattern = re.compile('rId\d+')
  341. for graph in self.docx.paragraphs:
  342. for run in graph.runs:
  343. if run.text == '':
  344. try:
  345. if not pattern.search(run.element.xml):
  346. continue
  347. content_id = pattern.search(run.element.xml).group(0)
  348. content_type = self.docx.part.related_parts[content_id].content_type
  349. except Exception as e:
  350. print("docx no image!", e)
  351. continue
  352. if not content_type.startswith('image'):
  353. continue
  354. img_data = self.docx.part.related_parts[content_id].blob
  355. if img_data is not None:
  356. image_list.append(img_data)
  357. return image_list
  358. @memory_decorator
  359. def get_orders(self):
  360. # 解析document.xml,获取文字顺序
  361. order_and_text_list = read_xml_order(self.path, self.unique_type_dir)
  362. return order_and_text_list
  363. def get_doc_object(self):
  364. return self._doc
  365. def get_html(self):
  366. try:
  367. self.convert()
  368. except:
  369. traceback.print_exc()
  370. self._doc.error_code = [-1]
  371. if self._doc.error_code is not None:
  372. return self._doc.error_code
  373. return self._doc.get_html()