Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

excel_parser.py 6.0KB

Add fallback to use 'calamine' parse engine in excel_parser.py (#9374) ### What problem does this PR solve? add fallback to `calamine` engine when parse error raised using the default `openpyxl` / `xlrd` engine. e.g. the following error can be fixed: ``` Traceback (most recent call last): File "/ragflow/deepdoc/parser/excel_parser.py", line 53, in _load_excel_to_workbook df = pd.read_excel(file_like_object) File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 495, in read_excel io = ExcelFile( File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 1567, in __init__ self._reader = self._engines[engine]( File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 46, in __init__ super().__init__( File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_base.py", line 573, in __init__ self.book = self.load_workbook(self.handles.handle, engine_kwargs) File "/ragflow/.venv/lib/python3.10/site-packages/pandas/io/excel/_xlrd.py", line 63, in load_workbook return open_workbook(file_contents=data, **engine_kwargs) File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/__init__.py", line 172, in open_workbook bk = open_workbook_xls( File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 68, in open_workbook_xls bk.biff2_8_load( File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/book.py", line 641, in biff2_8_load cd.locate_named_stream(UNICODE_LITERAL(qname)) File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 398, in locate_named_stream result = self._locate_stream( File "/ragflow/.venv/lib/python3.10/site-packages/xlrd/compdoc.py", line 429, in _locate_stream raise CompDocError("%s corruption: seen[%d] == %d" % (qname, s, self.seen[s])) xlrd.compdoc.CompDocError: Workbook corruption: seen[2] == 4 ``` ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue)
pirms 2 mēnešiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
  76. wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
  77. tb_chunks = []
  78. for sheetname in wb.sheetnames:
  79. ws = wb[sheetname]
  80. rows = list(ws.rows)
  81. if not rows:
  82. continue
  83. tb_rows_0 = "<tr>"
  84. for t in list(rows[0]):
  85. tb_rows_0 += f"<th>{t.value}</th>"
  86. tb_rows_0 += "</tr>"
  87. for chunk_i in range((len(rows) - 1) // chunk_rows + 1):
  88. tb = ""
  89. tb += f"<table><caption>{sheetname}</caption>"
  90. tb += tb_rows_0
  91. for r in list(
  92. rows[1 + chunk_i * chunk_rows: 1 + (chunk_i + 1) * chunk_rows]
  93. ):
  94. tb += "<tr>"
  95. for i, c in enumerate(r):
  96. if c.value is None:
  97. tb += "<td></td>"
  98. else:
  99. tb += f"<td>{c.value}</td>"
  100. tb += "</tr>"
  101. tb += "</table>\n"
  102. tb_chunks.append(tb)
  103. return tb_chunks
  104. def __call__(self, fnm):
  105. file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
  106. wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
  107. res = []
  108. for sheetname in wb.sheetnames:
  109. ws = wb[sheetname]
  110. rows = list(ws.rows)
  111. if not rows:
  112. continue
  113. ti = list(rows[0])
  114. for r in list(rows[1:]):
  115. fields = []
  116. for i, c in enumerate(r):
  117. if not c.value:
  118. continue
  119. t = str(ti[i].value) if i < len(ti) else ""
  120. t += (":" if t else "") + str(c.value)
  121. fields.append(t)
  122. line = "; ".join(fields)
  123. if sheetname.lower().find("sheet") < 0:
  124. line += " ——" + sheetname
  125. res.append(line)
  126. return res
  127. @staticmethod
  128. def row_number(fnm, binary):
  129. if fnm.split(".")[-1].lower().find("xls") >= 0:
  130. wb = RAGFlowExcelParser._load_excel_to_workbook(BytesIO(binary))
  131. total = 0
  132. for sheetname in wb.sheetnames:
  133. ws = wb[sheetname]
  134. total += len(list(ws.rows))
  135. return total
  136. if fnm.split(".")[-1].lower() in ["csv", "txt"]:
  137. encoding = find_codec(binary)
  138. txt = binary.decode(encoding, errors="ignore")
  139. return len(txt.split("\n"))
  140. if __name__ == "__main__":
  141. psr = RAGFlowExcelParser()
  142. psr(sys.argv[1])