Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1 год назад
1 год назад
1 год назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. from openpyxl import load_workbook, Workbook
  15. import sys
  16. from io import BytesIO
  17. from rag.nlp import find_codec
  18. import pandas as pd
  19. class RAGFlowExcelParser:
  20. @staticmethod
  21. def _load_excel_to_workbook(file_like_object):
  22. try:
  23. return load_workbook(file_like_object)
  24. except Exception as e:
  25. logging.info(f"****wxy: openpyxl load error: {e}, try pandas instead")
  26. try:
  27. df = pd.read_excel(file_like_object)
  28. wb = Workbook()
  29. ws = wb.active
  30. ws.title = "Data"
  31. for col_num, column_name in enumerate(df.columns, 1):
  32. ws.cell(row=1, column=col_num, value=column_name)
  33. for row_num, row in enumerate(df.values, 2):
  34. for col_num, value in enumerate(row, 1):
  35. ws.cell(row=row_num, column=col_num, value=value)
  36. return wb
  37. except Exception as e_pandas:
  38. raise Exception(f"****wxy: pandas read error: {e_pandas}, original openpyxl error: {e}")
  39. def html(self, fnm, chunk_rows=256):
  40. file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
  41. wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
  42. tb_chunks = []
  43. for sheetname in wb.sheetnames:
  44. ws = wb[sheetname]
  45. rows = list(ws.rows)
  46. if not rows:
  47. continue
  48. tb_rows_0 = "<tr>"
  49. for t in list(rows[0]):
  50. tb_rows_0 += f"<th>{t.value}</th>"
  51. tb_rows_0 += "</tr>"
  52. for chunk_i in range((len(rows) - 1) // chunk_rows + 1):
  53. tb = ""
  54. tb += f"<table><caption>{sheetname}</caption>"
  55. tb += tb_rows_0
  56. for r in list(
  57. rows[1 + chunk_i * chunk_rows: 1 + (chunk_i + 1) * chunk_rows]
  58. ):
  59. tb += "<tr>"
  60. for i, c in enumerate(r):
  61. if c.value is None:
  62. tb += "<td></td>"
  63. else:
  64. tb += f"<td>{c.value}</td>"
  65. tb += "</tr>"
  66. tb += "</table>\n"
  67. tb_chunks.append(tb)
  68. return tb_chunks
  69. def __call__(self, fnm):
  70. file_like_object = BytesIO(fnm) if not isinstance(fnm, str) else fnm
  71. wb = RAGFlowExcelParser._load_excel_to_workbook(file_like_object)
  72. res = []
  73. for sheetname in wb.sheetnames:
  74. ws = wb[sheetname]
  75. rows = list(ws.rows)
  76. if not rows:
  77. continue
  78. ti = list(rows[0])
  79. for r in list(rows[1:]):
  80. fields = []
  81. for i, c in enumerate(r):
  82. if not c.value:
  83. continue
  84. t = str(ti[i].value) if i < len(ti) else ""
  85. t += (":" if t else "") + str(c.value)
  86. fields.append(t)
  87. line = "; ".join(fields)
  88. if sheetname.lower().find("sheet") < 0:
  89. line += " ——" + sheetname
  90. res.append(line)
  91. return res
  92. @staticmethod
  93. def row_number(fnm, binary):
  94. if fnm.split(".")[-1].lower().find("xls") >= 0:
  95. wb = RAGFlowExcelParser._load_excel_to_workbook(BytesIO(binary))
  96. total = 0
  97. for sheetname in wb.sheetnames:
  98. ws = wb[sheetname]
  99. total += len(list(ws.rows))
  100. return total
  101. if fnm.split(".")[-1].lower() in ["csv", "txt"]:
  102. encoding = find_codec(binary)
  103. txt = binary.decode(encoding, errors="ignore")
  104. return len(txt.split("\n"))
  105. if __name__ == "__main__":
  106. psr = RAGFlowExcelParser()
  107. psr(sys.argv[1])