convert_docx.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import os
  2. import sys
  3. sys.path.append(os.path.dirname(__file__) + "/../")
  4. from format_convert.convert_tree import _Document, _Sentence, _Page, _Image, _Table
  5. import logging
  6. import re
  7. import traceback
  8. import xml
  9. import zipfile
  10. import docx
  11. import timeout_decorator
  12. from format_convert import get_memory_info
  13. from format_convert.convert_image import picture2text
  14. from format_convert.utils import judge_error_code, add_div
  15. @get_memory_info.memory_decorator
  16. def docx2text(path, unique_type_dir):
  17. logging.info("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. logging.info("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>" + "\n")
  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. logging.info("docx2text error!")
  100. print("docx2text", traceback.print_exc())
  101. return [-1]
  102. @get_memory_info.memory_decorator
  103. def read_xml_order(path, save_path):
  104. logging.info("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. logging.info("docx format error!")
  114. return [-3]
  115. try:
  116. collection = xml_analyze(save_path + "word/document.xml")
  117. except TimeoutError:
  118. logging.info("read_xml_order 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. logging.info("read_xml_order error!")
  151. print("read_xml_order", traceback.print_exc())
  152. # log_traceback("read_xml_order")
  153. return [-1]
  154. @get_memory_info.memory_decorator
  155. def read_xml_table(path, save_path):
  156. logging.info("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. logging.info("docx format error!")
  167. return [-3]
  168. try:
  169. collection = xml_analyze(save_path + "word/document.xml")
  170. except TimeoutError:
  171. logging.info("read_xml_table timeout")
  172. return [-4]
  173. body = collection.getElementsByTagName("w:body")[0]
  174. table_text_list = []
  175. # print("body.childNodes", body.childNodes)
  176. for line in body.childNodes:
  177. if "w:tbl" in str(line):
  178. # print("str(line)", str(line))
  179. table_text = '<table border="1">' + "\n"
  180. tr_list = line.getElementsByTagName("w:tr")
  181. # print("line.childNodes", line.childNodes)
  182. tr_index = 0
  183. tr_text_list = []
  184. tr_text_list_colspan = []
  185. for tr in tr_list:
  186. table_text = table_text + "<tr rowspan=1>" + "\n"
  187. tc_list = tr.getElementsByTagName("w:tc")
  188. tc_index = 0
  189. tc_text_list = []
  190. for tc in tc_list:
  191. tc_text = ""
  192. # 获取一格占多少列
  193. col_span = tc.getElementsByTagName("w:gridSpan")
  194. if col_span:
  195. col_span = int(col_span[0].getAttribute("w:val"))
  196. else:
  197. col_span = 1
  198. # 获取是否是合并单元格的下一个空单元格
  199. is_merge = tc.getElementsByTagName("w:vMerge")
  200. if is_merge:
  201. is_merge = is_merge[0].getAttribute("w:val")
  202. if is_merge == "continue":
  203. col_span_index = 0
  204. real_tc_index = 0
  205. # if get_platform() == "Windows":
  206. # print("read_xml_table tr_text_list", tr_text_list)
  207. # print("read_xml_table tr_index", tr_index)
  208. if 0 <= tr_index - 1 < len(tr_text_list):
  209. for tc_colspan in tr_text_list[tr_index - 1]:
  210. if col_span_index < tc_index:
  211. col_span_index += tc_colspan[1]
  212. real_tc_index += 1
  213. # print("tr_index-1, real_tc_index", tr_index-1, real_tc_index)
  214. # print(tr_text_list[tr_index-1])
  215. if real_tc_index < len(tr_text_list[tr_index - 1]):
  216. tc_text = tr_text_list[tr_index - 1][real_tc_index][0]
  217. table_text = table_text + "<td colspan=" + str(col_span) + ">" + "\n"
  218. p_list = tc.getElementsByTagName("w:p")
  219. for p in p_list:
  220. t = p.getElementsByTagName("w:t")
  221. if t:
  222. for tt in t:
  223. # print("tt", tt.childNodes)
  224. if len(tt.childNodes) > 0:
  225. tc_text += tt.childNodes[0].nodeValue
  226. tc_text += "\n"
  227. table_text = table_text + tc_text + "</td>" + "\n"
  228. tc_index += 1
  229. tc_text_list.append([tc_text, col_span])
  230. table_text += "</tr>" + "\n"
  231. tr_index += 1
  232. tr_text_list.append(tc_text_list)
  233. table_text += "</table>" + "\n"
  234. table_text_list.append(table_text)
  235. return table_text_list
  236. except Exception as e:
  237. logging.info("read_xml_table error")
  238. print("read_xml_table", traceback.print_exc())
  239. return [-1]
  240. @get_memory_info.memory_decorator
  241. @timeout_decorator.timeout(300, 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>\n"
  251. # print("==================")
  252. for row in table.rows:
  253. table_text += "<tr>\n"
  254. for cell in row.cells:
  255. table_text += "<td>" + cell.text + "</td>\n"
  256. table_text += "</tr>\n"
  257. table_text += "</table>\n"
  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. def init_package(self):
  267. # 各个包初始化
  268. try:
  269. self.docx = docx.Document(self.path)
  270. self.zip = zipfile.ZipFile(self.path)
  271. except:
  272. logging.info("cannot open docx!")
  273. traceback.print_exc()
  274. self._doc.error_code = [-3]
  275. def convert(self):
  276. self.init_package()
  277. if self._doc.error_code is not None:
  278. return
  279. order_and_text_list = self.get_orders()
  280. if judge_error_code(order_and_text_list):
  281. self._doc.error_code = order_and_text_list
  282. return
  283. order_list, text_list = order_and_text_list
  284. print("doc ", text_list[:10])
  285. table_list = self.get_tables()
  286. if judge_error_code(table_list):
  287. self._doc.error_code = table_list
  288. return
  289. # paragraph_list = self.get_paragraphs()
  290. image_list = self.get_images()
  291. temp_image_path = self.unique_type_dir + "temp_image.png"
  292. self._page = _Page(None, 0)
  293. order_y = 0
  294. for tag in order_list:
  295. bbox = (0, order_y, 0, 0)
  296. if tag == "w:t":
  297. if len(text_list) > 0:
  298. _para = text_list.pop(0)
  299. self._page.add_child(_Sentence(_para, bbox))
  300. if tag == "wp:docPr":
  301. if len(image_list) > 0:
  302. _image = image_list.pop(0)
  303. self._page.add_child(_Image(_image, temp_image_path, bbox))
  304. if tag == "w:tbl":
  305. if len(table_list) > 0:
  306. _table = table_list.pop(0)
  307. _table = _Table(_table, bbox)
  308. _table.is_html = True
  309. self._page.add_child(_table)
  310. order_y += 1
  311. if self._doc.error_code is None and self._page.error_code is not None:
  312. self._doc.error_code = self._page.error_code
  313. self._doc.add_child(self._page)
  314. def get_paragraphs(self):
  315. # 遍历段落
  316. paragraph_list = []
  317. for paragraph in self.docx.paragraphs:
  318. if paragraph.text != "":
  319. paragraph_list.append(paragraph.text)
  320. return paragraph_list
  321. def get_tables(self):
  322. # 遍历表
  323. table_list = read_xml_table(self.path, self.unique_type_dir)
  324. return table_list
  325. def get_images(self):
  326. # 顺序遍历图片
  327. image_list = []
  328. pattern = re.compile('rId\d+')
  329. for graph in self.docx.paragraphs:
  330. for run in graph.runs:
  331. if run.text == '':
  332. try:
  333. if not pattern.search(run.element.xml):
  334. continue
  335. content_id = pattern.search(run.element.xml).group(0)
  336. content_type = self.docx.part.related_parts[content_id].content_type
  337. except Exception as e:
  338. print("docx no image!", e)
  339. continue
  340. if not content_type.startswith('image'):
  341. continue
  342. img_data = self.docx.part.related_parts[content_id].blob
  343. if img_data is not None:
  344. image_list.append(img_data)
  345. return image_list
  346. def get_orders(self):
  347. # 解析document.xml,获取文字顺序
  348. order_and_text_list = read_xml_order(self.path, self.unique_type_dir)
  349. return order_and_text_list
  350. def get_doc_object(self):
  351. return self._doc
  352. def get_html(self):
  353. try:
  354. self.convert()
  355. except:
  356. traceback.print_exc()
  357. self._doc.error_code = [-1]
  358. if self._doc.error_code is not None:
  359. return self._doc.error_code
  360. return self._doc.get_html()