2024-06-01 16:24:10 +08:00
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
|
#
|
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
#
|
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
|
# limitations under the License.
|
|
|
|
|
#
|
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
import logging
|
2024-01-15 08:46:22 +08:00
|
|
|
|
import sys
|
|
|
|
|
from io import BytesIO
|
|
|
|
|
|
2025-02-12 12:39:25 +08:00
|
|
|
|
import pandas as pd
|
2025-03-12 19:20:50 +08:00
|
|
|
|
from openpyxl import Workbook, load_workbook
|
|
|
|
|
|
|
|
|
|
from rag.nlp import find_codec
|
2025-02-12 12:39:25 +08:00
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
2024-04-28 13:19:54 +08:00
|
|
|
|
class RAGFlowExcelParser:
|
2025-03-12 19:20:50 +08:00
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
def _load_excel_to_workbook(file_like_object):
|
2025-03-12 19:20:50 +08:00
|
|
|
|
if isinstance(file_like_object, bytes):
|
|
|
|
|
file_like_object = BytesIO(file_like_object)
|
|
|
|
|
|
|
|
|
|
# Read first 4 bytes to determine file type
|
|
|
|
|
file_like_object.seek(0)
|
|
|
|
|
file_head = file_like_object.read(4)
|
|
|
|
|
file_like_object.seek(0)
|
|
|
|
|
|
|
|
|
|
if not (file_head.startswith(b'PK\x03\x04') or file_head.startswith(b'\xD0\xCF\x11\xE0')):
|
|
|
|
|
logging.info("****wxy: Not an Excel file, converting CSV to Excel Workbook")
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
file_like_object.seek(0)
|
|
|
|
|
df = pd.read_csv(file_like_object)
|
|
|
|
|
return RAGFlowExcelParser._dataframe_to_workbook(df)
|
|
|
|
|
|
|
|
|
|
except Exception as e_csv:
|
|
|
|
|
raise Exception(f"****wxy: Failed to parse CSV and convert to Excel Workbook: {e_csv}")
|
|
|
|
|
|
2025-02-12 12:39:25 +08:00
|
|
|
|
try:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
return load_workbook(file_like_object)
|
2025-02-12 12:39:25 +08:00
|
|
|
|
except Exception as e:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
logging.info(f"****wxy: openpyxl load error: {e}, try pandas instead")
|
|
|
|
|
try:
|
2025-03-12 19:20:50 +08:00
|
|
|
|
file_like_object.seek(0)
|
2025-03-05 11:55:27 +08:00
|
|
|
|
df = pd.read_excel(file_like_object)
|
2025-03-12 19:20:50 +08:00
|
|
|
|
return RAGFlowExcelParser._dataframe_to_workbook(df)
|
2025-03-05 11:55:27 +08:00
|
|
|
|
except Exception as e_pandas:
|
2025-03-12 19:20:50 +08:00
|
|
|
|
raise Exception(f"****wxy: pandas.read_excel error: {e_pandas}, original openpyxl error: {e}")
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _dataframe_to_workbook(df):
|
|
|
|
|
wb = Workbook()
|
|
|
|
|
ws = wb.active
|
|
|
|
|
ws.title = "Data"
|
|
|
|
|
|
|
|
|
|
for col_num, column_name in enumerate(df.columns, 1):
|
|
|
|
|
ws.cell(row=1, column=col_num, value=column_name)
|
|
|
|
|
|
|
|
|
|
for row_num, row in enumerate(df.values, 2):
|
|
|
|
|
for col_num, value in enumerate(row, 1):
|
|
|
|
|
ws.cell(row=row_num, column=col_num, value=value)
|
|
|
|
|
|
|
|
|
|
return wb
|
2024-05-20 18:35:15 +08:00
|
|
|
|
|
2025-03-05 11:55:27 +08:00
|
|
|
|
def html(self, fnm, chunk_rows=256):
|
|
|
|
|
file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
|
|
|
|
|
wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb_chunks = []
|
2024-03-20 16:56:16 +08:00
|
|
|
|
for sheetname in wb.sheetnames:
|
|
|
|
|
ws = wb[sheetname]
|
|
|
|
|
rows = list(ws.rows)
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not rows:
|
|
|
|
|
continue
|
2024-05-20 18:35:15 +08:00
|
|
|
|
|
|
|
|
|
tb_rows_0 = "<tr>"
|
2024-03-27 11:33:46 +08:00
|
|
|
|
for t in list(rows[0]):
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb_rows_0 += f"<th>{t.value}</th>"
|
|
|
|
|
tb_rows_0 += "</tr>"
|
|
|
|
|
|
|
|
|
|
for chunk_i in range((len(rows) - 1) // chunk_rows + 1):
|
|
|
|
|
tb = ""
|
|
|
|
|
tb += f"<table><caption>{sheetname}</caption>"
|
|
|
|
|
tb += tb_rows_0
|
2024-12-08 14:21:12 +08:00
|
|
|
|
for r in list(
|
2025-03-12 19:20:50 +08:00
|
|
|
|
rows[1 + chunk_i * chunk_rows: 1 + (chunk_i + 1) * chunk_rows]
|
2024-12-08 14:21:12 +08:00
|
|
|
|
):
|
2024-05-20 18:35:15 +08:00
|
|
|
|
tb += "<tr>"
|
|
|
|
|
for i, c in enumerate(r):
|
|
|
|
|
if c.value is None:
|
|
|
|
|
tb += "<td></td>"
|
|
|
|
|
else:
|
|
|
|
|
tb += f"<td>{c.value}</td>"
|
|
|
|
|
tb += "</tr>"
|
|
|
|
|
tb += "</table>\n"
|
|
|
|
|
tb_chunks.append(tb)
|
|
|
|
|
|
|
|
|
|
return tb_chunks
|
2024-03-20 16:56:16 +08:00
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
def __call__(self, fnm):
|
2025-03-05 11:55:27 +08:00
|
|
|
|
file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
|
|
|
|
|
wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
|
2025-02-12 12:39:25 +08:00
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
res = []
|
|
|
|
|
for sheetname in wb.sheetnames:
|
|
|
|
|
ws = wb[sheetname]
|
|
|
|
|
rows = list(ws.rows)
|
2024-12-08 14:21:12 +08:00
|
|
|
|
if not rows:
|
|
|
|
|
continue
|
2024-01-15 08:46:22 +08:00
|
|
|
|
ti = list(rows[0])
|
|
|
|
|
for r in list(rows[1:]):
|
2024-12-08 14:21:12 +08:00
|
|
|
|
fields = []
|
2024-03-27 11:33:46 +08:00
|
|
|
|
for i, c in enumerate(r):
|
|
|
|
|
if not c.value:
|
|
|
|
|
continue
|
2024-01-15 08:46:22 +08:00
|
|
|
|
t = str(ti[i].value) if i < len(ti) else ""
|
2024-03-12 11:57:08 +08:00
|
|
|
|
t += (":" if t else "") + str(c.value)
|
2024-12-08 14:21:12 +08:00
|
|
|
|
fields.append(t)
|
|
|
|
|
line = "; ".join(fields)
|
2024-03-27 11:33:46 +08:00
|
|
|
|
if sheetname.lower().find("sheet") < 0:
|
2024-12-08 14:21:12 +08:00
|
|
|
|
line += " ——" + sheetname
|
|
|
|
|
res.append(line)
|
2024-01-15 08:46:22 +08:00
|
|
|
|
return res
|
|
|
|
|
|
2024-03-12 11:57:08 +08:00
|
|
|
|
@staticmethod
|
|
|
|
|
def row_number(fnm, binary):
|
|
|
|
|
if fnm.split(".")[-1].lower().find("xls") >= 0:
|
2025-03-05 11:55:27 +08:00
|
|
|
|
wb = RAGFlowExcelParser._load_excel_to_workbook(BytesIO(binary))
|
2024-03-12 11:57:08 +08:00
|
|
|
|
total = 0
|
|
|
|
|
for sheetname in wb.sheetnames:
|
|
|
|
|
ws = wb[sheetname]
|
2024-03-14 19:45:29 +08:00
|
|
|
|
total += len(list(ws.rows))
|
2024-12-19 17:30:26 +08:00
|
|
|
|
return total
|
2024-03-12 11:57:08 +08:00
|
|
|
|
|
|
|
|
|
if fnm.split(".")[-1].lower() in ["csv", "txt"]:
|
2024-04-19 18:02:53 +08:00
|
|
|
|
encoding = find_codec(binary)
|
2024-05-07 12:25:47 +08:00
|
|
|
|
txt = binary.decode(encoding, errors="ignore")
|
2024-03-12 11:57:08 +08:00
|
|
|
|
return len(txt.split("\n"))
|
|
|
|
|
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2024-04-28 13:19:54 +08:00
|
|
|
|
psr = RAGFlowExcelParser()
|
2024-01-15 08:46:22 +08:00
|
|
|
|
psr(sys.argv[1])
|