convert_zip.py 7.1 KB

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