convert_zip.py 6.6 KB

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