您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

excel_parser.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import logging
  14. import re
  15. import sys
  16. from io import BytesIO
  17. import pandas as pd
  18. from openpyxl import Workbook, load_workbook
  19. from rag.nlp import find_codec
  20. # copied from `/openpyxl/cell/cell.py`
  21. ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]')
  22. class RAGFlowExcelParser:
  23. @staticmethod
  24. def _load_excel_to_workbook(file_like_object):
  25. if isinstance(file_like_object, bytes):
  26. file_like_object = BytesIO(file_like_object)
  27. # Read first 4 bytes to determine file type
  28. file_like_object.seek(0)
  29. file_head = file_like_object.read(4)
  30. file_like_object.seek(0)
  31. if not (file_head.startswith(b'PK\x03\x04') or file_head.startswith(b'\xD0\xCF\x11\xE0')):
  32. logging.info("Not an Excel file, converting CSV to Excel Workbook")
  33. try:
  34. file_like_object.seek(0)
  35. df = pd.read_csv(file_like_object)
  36. return RAGFlowExcelParser._dataframe_to_workbook(df)
  37. except Exception as e_csv:
  38. raise Exception(f"Failed to parse CSV and convert to Excel Workbook: {e_csv}")
  39. try:
  40. return load_workbook(file_like_object,data_only= True)
  41. except Exception as e:
  42. logging.info(f"openpyxl load error: {e}, try pandas instead")
  43. try:
  44. file_like_object.seek(0)
  45. try:
  46. df = pd.read_excel(file_like_object)
  47. return RAGFlowExcelParser._dataframe_to_workbook(df)
  48. except Exception as ex:
  49. logging.info(f"pandas with default engine load error: {ex}, try calamine instead")
  50. file_like_object.seek(0)
  51. df = pd.read_excel(file_like_object, engine='calamine')
  52. return RAGFlowExcelParser._dataframe_to_workbook(df)
  53. except Exception as e_pandas:
  54. raise Exception(f"pandas.read_excel error: {e_pandas}, original openpyxl error: {e}")
  55. @staticmethod
  56. def _clean_dataframe(df: pd.DataFrame):
  57. def clean_string(s):
  58. if isinstance(s, str):
  59. return ILLEGAL_CHARACTERS_RE.sub(" ", s)
  60. return s
  61. return df.apply(lambda col: col.map(clean_string))
  62. @staticmethod
  63. def _dataframe_to_workbook(df):
  64. df = RAGFlowExcelParser._clean_dataframe(df)
  65. wb = Workbook()
  66. ws = wb.active
  67. ws.title = "Data"
  68. for col_num, column_name in enumerate(df.columns, 1):
  69. ws.cell(row=1, column=col_num, value=column_name)
  70. for row_num, row in enumerate(df.values, 2):
  71. for col_num, value in enumerate(row, 1):
  72. ws.cell(row=row_num, column=col_num, value=value)
  73. return wb
  74. def html(self, fnm, chunk_rows=256):
  75. from html import escape
  76. file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
  77. wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
  78. tb_chunks = []
  79. def _fmt(v):
  80. if v is None:
  81. return ""
  82. return str(v).strip()
  83. for sheetname in wb.sheetnames:
  84. ws = wb[sheetname]
  85. rows = list(ws.rows)
  86. if not rows:
  87. continue
  88. tb_rows_0 = "<tr>"
  89. for t in list(rows[0]):
  90. tb_rows_0 += f"<th>{escape(_fmt(t.value))}</th>"
  91. tb_rows_0 += "</tr>"
  92. for chunk_i in range((len(rows) - 1) // chunk_rows + 1):
  93. tb = ""
  94. tb += f"<table><caption>{sheetname}</caption>"
  95. tb += tb_rows_0
  96. for r in list(
  97. rows[1 + chunk_i * chunk_rows: min(1 + (chunk_i + 1) * chunk_rows, len(rows))]
  98. ):
  99. tb += "<tr>"
  100. for i, c in enumerate(r):
  101. if c.value is None:
  102. tb += "<td></td>"
  103. else:
  104. tb += f"<td>{c.value}</td>"
  105. tb += "</tr>"
  106. tb += "</table>\n"
  107. tb_chunks.append(tb)
  108. return tb_chunks
  109. def __call__(self, fnm):
  110. file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
  111. wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
  112. res = []
  113. for sheetname in wb.sheetnames:
  114. ws = wb[sheetname]
  115. rows = list(ws.rows)
  116. if not rows:
  117. continue
  118. ti = list(rows[0])
  119. for r in list(rows[1:]):
  120. fields = []
  121. for i, c in enumerate(r):
  122. if not c.value:
  123. continue
  124. t = str(ti[i].value) if i < len(ti) else ""
  125. t += (":" if t else "") + str(c.value)
  126. fields.append(t)
  127. line = "; ".join(fields)
  128. if sheetname.lower().find("sheet") < 0:
  129. line += " ——" + sheetname
  130. res.append(line)
  131. return res
  132. @staticmethod
  133. def row_number(fnm, binary):
  134. if fnm.split(".")[-1].lower().find("xls") >= 0:
  135. wb = RAGFlowExcelParser._load_excel_to_workbook(BytesIO(binary))
  136. total = 0
  137. for sheetname in wb.sheetnames:
  138. ws = wb[sheetname]
  139. total += len(list(ws.rows))
  140. return total
  141. if fnm.split(".")[-1].lower() in ["csv", "txt"]:
  142. encoding = find_codec(binary)
  143. txt = binary.decode(encoding, errors="ignore")
  144. return len(txt.split("\n"))
  145. if __name__ == "__main__":
  146. psr = RAGFlowExcelParser()
  147. psr(sys.argv[1])