convert_docx.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. temp_text += t.childNodes[0].nodeValue
  133. text_list.append(temp_text)
  134. if picture:
  135. order_list.append("wp:docPr")
  136. for line1 in line.childNodes:
  137. if "w:r" in str(line1):
  138. # print("read_xml_order", "w:r")
  139. picture1 = line1.getElementsByTagName("w:pict")
  140. if picture1:
  141. order_list.append("wp:docPr")
  142. if "w:tbl" in str(line):
  143. order_list.append("w:tbl")
  144. read_xml_table(path, save_path)
  145. return [order_list, text_list]
  146. except Exception as e:
  147. logging.info("read_xml_order error!")
  148. print("read_xml_order", traceback.print_exc())
  149. # log_traceback("read_xml_order")
  150. return [-1]
  151. @get_memory_info.memory_decorator
  152. def read_xml_table(path, save_path):
  153. logging.info("into read_xml_table")
  154. try:
  155. try:
  156. f = zipfile.ZipFile(path)
  157. for file in f.namelist():
  158. if "word/document.xml" == str(file):
  159. f.extract(file, save_path)
  160. f.close()
  161. except Exception as e:
  162. # print("docx format error!", e)
  163. logging.info("docx format error!")
  164. return [-3]
  165. try:
  166. collection = xml_analyze(save_path + "word/document.xml")
  167. except TimeoutError:
  168. logging.info("read_xml_table timeout")
  169. return [-4]
  170. body = collection.getElementsByTagName("w:body")[0]
  171. table_text_list = []
  172. # print("body.childNodes", body.childNodes)
  173. for line in body.childNodes:
  174. if "w:tbl" in str(line):
  175. # print("str(line)", str(line))
  176. table_text = '<table border="1">' + "\n"
  177. tr_list = line.getElementsByTagName("w:tr")
  178. # print("line.childNodes", line.childNodes)
  179. tr_index = 0
  180. tr_text_list = []
  181. tr_text_list_colspan = []
  182. for tr in tr_list:
  183. table_text = table_text + "<tr rowspan=1>" + "\n"
  184. tc_list = tr.getElementsByTagName("w:tc")
  185. tc_index = 0
  186. tc_text_list = []
  187. for tc in tc_list:
  188. tc_text = ""
  189. # 获取一格占多少列
  190. col_span = tc.getElementsByTagName("w:gridSpan")
  191. if col_span:
  192. col_span = int(col_span[0].getAttribute("w:val"))
  193. else:
  194. col_span = 1
  195. # 获取是否是合并单元格的下一个空单元格
  196. is_merge = tc.getElementsByTagName("w:vMerge")
  197. if is_merge:
  198. is_merge = is_merge[0].getAttribute("w:val")
  199. if is_merge == "continue":
  200. col_span_index = 0
  201. real_tc_index = 0
  202. # if get_platform() == "Windows":
  203. # print("read_xml_table tr_text_list", tr_text_list)
  204. # print("read_xml_table tr_index", tr_index)
  205. if 0 <= tr_index - 1 < len(tr_text_list):
  206. for tc_colspan in tr_text_list[tr_index - 1]:
  207. if col_span_index < tc_index:
  208. col_span_index += tc_colspan[1]
  209. real_tc_index += 1
  210. # print("tr_index-1, real_tc_index", tr_index-1, real_tc_index)
  211. # print(tr_text_list[tr_index-1])
  212. if real_tc_index < len(tr_text_list[tr_index - 1]):
  213. tc_text = tr_text_list[tr_index - 1][real_tc_index][0]
  214. table_text = table_text + "<td colspan=" + str(col_span) + ">" + "\n"
  215. p_list = tc.getElementsByTagName("w:p")
  216. for p in p_list:
  217. t = p.getElementsByTagName("w:t")
  218. if t:
  219. for tt in t:
  220. # print("tt", tt.childNodes)
  221. if len(tt.childNodes) > 0:
  222. tc_text += tt.childNodes[0].nodeValue
  223. tc_text += "\n"
  224. table_text = table_text + tc_text + "</td>" + "\n"
  225. tc_index += 1
  226. tc_text_list.append([tc_text, col_span])
  227. table_text += "</tr>" + "\n"
  228. tr_index += 1
  229. tr_text_list.append(tc_text_list)
  230. table_text += "</table>" + "\n"
  231. table_text_list.append(table_text)
  232. return table_text_list
  233. except Exception as e:
  234. logging.info("read_xml_table error")
  235. print("read_xml_table", traceback.print_exc())
  236. return [-1]
  237. @get_memory_info.memory_decorator
  238. @timeout_decorator.timeout(300, timeout_exception=TimeoutError)
  239. def xml_analyze(path):
  240. # 解析xml
  241. DOMTree = xml.dom.minidom.parse(path)
  242. collection = DOMTree.documentElement
  243. return collection
  244. def read_docx_table(document):
  245. table_text_list = []
  246. for table in document.tables:
  247. table_text = "<table>\n"
  248. # print("==================")
  249. for row in table.rows:
  250. table_text += "<tr>\n"
  251. for cell in row.cells:
  252. table_text += "<td>" + cell.text + "</td>\n"
  253. table_text += "</tr>\n"
  254. table_text += "</table>\n"
  255. # print(table_text)
  256. table_text_list.append(table_text)
  257. return table_text_list
  258. class DocxConvert:
  259. def __init__(self, path, unique_type_dir):
  260. self._doc = _Document(path)
  261. self.path = path
  262. self.unique_type_dir = unique_type_dir
  263. def init_package(self):
  264. # 各个包初始化
  265. try:
  266. self.docx = docx.Document(self.path)
  267. self.zip = zipfile.ZipFile(self.path)
  268. except:
  269. logging.info("cannot open docx!")
  270. traceback.print_exc()
  271. self._doc.error_code = [-3]
  272. def convert(self):
  273. self.init_package()
  274. if self._doc.error_code is not None:
  275. return
  276. order_and_text_list = self.get_orders()
  277. if judge_error_code(order_and_text_list):
  278. self._doc.error_code = order_and_text_list
  279. return
  280. order_list, text_list = order_and_text_list
  281. print("doc ", text_list[:10])
  282. table_list = self.get_tables()
  283. if judge_error_code(table_list):
  284. self._doc.error_code = table_list
  285. return
  286. # paragraph_list = self.get_paragraphs()
  287. image_list = self.get_images()
  288. self._page = _Page(None, 0)
  289. order_y = 0
  290. for tag in order_list:
  291. bbox = (0, order_y, 0, 0)
  292. if tag == "w:t":
  293. if len(text_list) > 0:
  294. _para = text_list.pop(0)
  295. self._page.add_child(_Sentence(_para, bbox))
  296. if tag == "wp:docPr":
  297. if len(image_list) > 0:
  298. _image = image_list.pop(0)
  299. self._page.add_child(_Image(_image, bbox))
  300. if tag == "w:tbl":
  301. if len(table_list) > 0:
  302. _table = table_list.pop(0)
  303. _table = _Table(_table, bbox)
  304. _table.is_html = True
  305. self._page.add_child(_table)
  306. order_y += 1
  307. if self._doc.error_code is None and self._page.error_code is not None:
  308. self._doc.error_code = self._page.error_code
  309. self._doc.add_child(self._page)
  310. def get_paragraphs(self):
  311. # 遍历段落
  312. paragraph_list = []
  313. for paragraph in self.docx.paragraphs:
  314. if paragraph.text != "":
  315. paragraph_list.append(paragraph.text)
  316. return paragraph_list
  317. def get_tables(self):
  318. # 遍历表
  319. table_list = read_xml_table(self.path, self.unique_type_dir)
  320. return table_list
  321. def get_images(self):
  322. # 顺序遍历图片
  323. image_list = []
  324. pattern = re.compile('rId\d+')
  325. for graph in self.docx.paragraphs:
  326. for run in graph.runs:
  327. if run.text == '':
  328. try:
  329. if not pattern.search(run.element.xml):
  330. continue
  331. content_id = pattern.search(run.element.xml).group(0)
  332. content_type = self.docx.part.related_parts[content_id].content_type
  333. except Exception as e:
  334. print("docx no image!", e)
  335. continue
  336. if not content_type.startswith('image'):
  337. continue
  338. img_data = self.docx.part.related_parts[content_id].blob
  339. if img_data is not None:
  340. image_list.append(img_data)
  341. return image_list
  342. def get_orders(self):
  343. # 解析document.xml,获取文字顺序
  344. order_and_text_list = read_xml_order(self.path, self.unique_type_dir)
  345. return order_and_text_list
  346. def get_doc_object(self):
  347. return self._doc
  348. def get_html(self):
  349. try:
  350. self.convert()
  351. except:
  352. traceback.print_exc()
  353. self._doc.error_code = [-1]
  354. if self._doc.error_code is not None:
  355. return self._doc.error_code
  356. return self._doc.get_html()