convert_zip.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import os
  2. import sys
  3. sys.path.append(os.path.dirname(__file__) + "/../")
  4. from format_convert.convert_tree import _Document, _Page, _Sentence
  5. import logging
  6. import traceback
  7. import zipfile
  8. from format_convert import get_memory_info
  9. from format_convert.utils import get_platform, rename_inner_files, judge_error_code, judge_format
  10. @get_memory_info.memory_decorator
  11. def zip2text(path, unique_type_dir):
  12. from format_convert.convert import getText
  13. logging.info("into zip2text")
  14. try:
  15. zip_path = unique_type_dir
  16. try:
  17. zip_file = zipfile.ZipFile(path)
  18. zip_list = zip_file.namelist()
  19. # print("zip list namelist", zip_list)
  20. if get_platform() == "Windows":
  21. if os.path.exists(zip_list[0]):
  22. print("zip2text exists")
  23. # 循环解压文件到指定目录
  24. file_list = []
  25. for f in zip_list:
  26. file_list.append(zip_file.extract(f, path=zip_path))
  27. # zip_file.extractall(path=zip_path)
  28. zip_file.close()
  29. # 获取文件名
  30. # file_list = []
  31. # for root, dirs, files in os.walk(zip_path, topdown=False):
  32. # for name in dirs:
  33. # file_list.append(os.path.join(root, name) + os.sep)
  34. # for name in files:
  35. # file_list.append(os.path.join(root, name))
  36. #
  37. # # if get_platform() == "Windows":
  38. # # print("file_list", file_list)
  39. #
  40. # # 过滤掉doc缓存文件
  41. # temp_list = []
  42. # for f in file_list:
  43. # if re.search("~\$", f):
  44. # continue
  45. # else:
  46. # temp_list.append(f)
  47. # file_list = temp_list
  48. except Exception as e:
  49. logging.info("zip format error!")
  50. print("zip format error!", traceback.print_exc())
  51. return [-3]
  52. # 内部文件重命名
  53. # file_list = inner_file_rename(file_list)
  54. file_list = rename_inner_files(zip_path)
  55. if judge_error_code(file_list):
  56. return file_list
  57. if get_platform() == "Windows":
  58. print("============= zip file list")
  59. # print(file_list)
  60. text = []
  61. for file in file_list:
  62. if os.path.isdir(file):
  63. continue
  64. # 无文件后缀,猜格式
  65. if len(file.split(".")) <= 1:
  66. logging.info(str(file) + " has no type! Guess type...")
  67. _type = judge_format(file)
  68. if _type is None:
  69. logging.info(str(file) + "cannot guess type!")
  70. sub_text = [""]
  71. else:
  72. logging.info(str(file) + " guess type: " + _type)
  73. new_file = str(file) + "." + _type
  74. os.rename(file, new_file)
  75. file = new_file
  76. sub_text = getText(_type, file)
  77. # 有文件后缀,截取
  78. else:
  79. _type = file.split(".")[-1]
  80. sub_text = getText(_type, file)
  81. if judge_error_code(sub_text, code=[-3]):
  82. continue
  83. if judge_error_code(sub_text):
  84. return sub_text
  85. text = text + sub_text
  86. return text
  87. except Exception as e:
  88. logging.info("zip2text error!")
  89. print("zip2text", traceback.print_exc())
  90. return [-1]
  91. class ZipConvert:
  92. def __init__(self, path, unique_type_dir):
  93. self._doc = _Document(path)
  94. self.path = path
  95. self.unique_type_dir = unique_type_dir
  96. self.zip_path = unique_type_dir
  97. def init_package(self):
  98. try:
  99. zip_file = zipfile.ZipFile(self.path)
  100. zip_list = zip_file.namelist()
  101. zip_list.sort(key=lambda x: len(x))
  102. # 循环解压文件到指定目录
  103. file_list = []
  104. new_zip_list = []
  105. for f in zip_list:
  106. # 中文乱码,会导致zip解压失败,直接修改对象
  107. try:
  108. new_f = f.encode('cp437').decode('gbk')
  109. except:
  110. new_f = f.encode('utf-8').decode('utf-8')
  111. if f != new_f:
  112. zip_file.NameToInfo[new_f] = zip_file.NameToInfo[f]
  113. zip_file.NameToInfo[new_f].filename = new_f
  114. zip_file.NameToInfo.pop(f)
  115. new_zip_list.append(new_f)
  116. new_zip_list.sort(key=lambda x: len(x))
  117. for f in new_zip_list:
  118. file_list.append(zip_file.extract(f, path=self.zip_path))
  119. zip_file.close()
  120. except:
  121. logging.info("cannot open zip!")
  122. traceback.print_exc()
  123. self._doc.error_code = [-3]
  124. def convert(self):
  125. from format_convert.convert import getText
  126. self.init_package()
  127. if self._doc.error_code is not None:
  128. return
  129. # 内部文件重命名
  130. file_list = rename_inner_files(self.zip_path)
  131. if judge_error_code(file_list):
  132. return file_list
  133. file_no = 0
  134. self._page = _Page(None, 0)
  135. for file in file_list:
  136. if os.path.isdir(file):
  137. continue
  138. bbox = (0, file_no, 0, 0)
  139. # 无文件后缀,猜格式
  140. if len(file.split(".")) <= 1:
  141. logging.info(str(file) + " has no type! Guess type...")
  142. _type = judge_format(file)
  143. if _type is None:
  144. logging.info(str(file) + "cannot guess type!")
  145. continue
  146. else:
  147. logging.info(str(file) + " guess type: " + _type)
  148. new_file = str(file) + "." + _type
  149. os.rename(file, new_file)
  150. file = new_file
  151. sub_html = getText(_type, file)
  152. # 有文件后缀,截取
  153. else:
  154. _type = file.split(".")[-1]
  155. sub_html = getText(_type, file)
  156. if judge_error_code(sub_html, code=[-3]):
  157. continue
  158. if judge_error_code(sub_html):
  159. self._doc.error_code = sub_html
  160. return
  161. _sen = _Sentence(sub_html[0], bbox, is_html=True)
  162. self._page.add_child(_sen)
  163. self._doc.add_child(self._page)
  164. def get_html(self):
  165. try:
  166. self.convert()
  167. except:
  168. traceback.print_exc()
  169. self._doc.error_code = [-1]
  170. if self._doc.error_code is not None:
  171. return self._doc.error_code
  172. return self._doc.get_html()