convert_zip.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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, page_no, time_out):
  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. self.page_no = page_no
  101. self.time_out = time_out
  102. @memory_decorator
  103. def init_package(self):
  104. try:
  105. zip_file = zipfile.ZipFile(self.path)
  106. zip_list = zip_file.namelist()
  107. zip_list.sort(key=lambda x: len(x))
  108. # 循环解压文件到指定目录
  109. file_list = []
  110. new_zip_list = []
  111. for f in zip_list:
  112. # 中文乱码,会导致zip解压失败,直接修改对象
  113. try:
  114. new_f = f.encode('cp437').decode('gbk')
  115. # print('1', new_f)
  116. except:
  117. new_f = f.encode('utf-8').decode('utf-8')
  118. # print('2', new_f)
  119. if f != new_f:
  120. new_f = str(uuid.uuid1().hex) + '.' + f.split('.')[-1]
  121. zip_file.NameToInfo[new_f] = zip_file.NameToInfo[f]
  122. zip_file.NameToInfo[new_f].filename = new_f
  123. zip_file.NameToInfo.pop(f)
  124. zip_file.NameToInfo[new_f].orig_filename = new_f
  125. # zip_file.NameToInfo[new_f].flag_bits = 2048
  126. zip_file.NameToInfo[new_f].has_changed_name = True
  127. new_zip_list.append(new_f)
  128. new_zip_list.sort(key=lambda x: len(x))
  129. for f in new_zip_list:
  130. file_list.append(zip_file.extract(f, path=self.zip_path))
  131. zip_file.close()
  132. except:
  133. log("cannot open zip!")
  134. traceback.print_exc()
  135. self._doc.error_code = [-3]
  136. def convert(self):
  137. from format_convert.convert import getText
  138. self.init_package()
  139. if self._doc.error_code is not None:
  140. return
  141. # 内部文件重命名
  142. file_list = rename_inner_files(self.zip_path)
  143. if judge_error_code(file_list):
  144. return file_list
  145. file_no = 0
  146. self._page = _Page(None, 0)
  147. for file in file_list:
  148. if os.path.isdir(file):
  149. continue
  150. bbox = (0, file_no, 0, 0)
  151. # 无文件后缀,猜格式
  152. if len(file.split(".")) <= 1:
  153. log(str(file) + " has no type! Guess type...")
  154. _type = judge_format(file)
  155. if _type is None:
  156. log(str(file) + "cannot guess type!")
  157. continue
  158. else:
  159. log(str(file) + " guess type: " + _type)
  160. new_file = str(file) + "." + _type
  161. os.rename(file, new_file)
  162. file = new_file
  163. sub_html = getText(_type, file)
  164. # 有文件后缀,截取
  165. else:
  166. _type = file.split(".")[-1]
  167. if _type in ['pdf']:
  168. sub_html = getText(_type, file, self.page_no, time_out=self.time_out)
  169. else:
  170. sub_html = getText(_type, file, time_out=self.time_out)
  171. # log('convert_zip.py sub_html ' + str(sub_html))
  172. # 文件报错也继续
  173. if judge_error_code(sub_html):
  174. continue
  175. # if judge_error_code(sub_html, code=[-3]):
  176. # continue
  177. # if judge_error_code(sub_html):
  178. # self._doc.error_code = sub_html
  179. # return
  180. _sen = _Sentence(sub_html[0], bbox, is_html=True)
  181. self._page.add_child(_sen)
  182. self._doc.add_child(self._page)
  183. def get_html(self):
  184. try:
  185. self.convert()
  186. except:
  187. traceback.print_exc()
  188. self._doc.error_code = [-1]
  189. if self._doc.error_code is not None:
  190. return self._doc.error_code
  191. return self._doc.get_html()
  192. if __name__ == '__main__':
  193. c = ZipConvert("C:/Users/Administrator/Downloads/3775865878373065499.zip", "C:/Users/Administrator/Downloads/1")
  194. c.get_html()