convert_zip.py 6.6 KB

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