2025-04-30 06:14:41 +00:00
|
|
|
|
# coding=utf-8
|
|
|
|
|
|
"""
|
|
|
|
|
|
@project: maxkb
|
|
|
|
|
|
@Author:虎
|
|
|
|
|
|
@file: csv_parse_qa_handle.py
|
|
|
|
|
|
@date:2024/5/21 14:59
|
|
|
|
|
|
@desc:
|
|
|
|
|
|
"""
|
|
|
|
|
|
import csv
|
|
|
|
|
|
import io
|
|
|
|
|
|
import os
|
2025-06-30 04:40:11 +00:00
|
|
|
|
import traceback
|
2025-04-30 06:14:41 +00:00
|
|
|
|
from typing import List
|
|
|
|
|
|
|
|
|
|
|
|
from charset_normalizer import detect
|
|
|
|
|
|
|
|
|
|
|
|
from common.handle.base_split_handle import BaseSplitHandle
|
2025-06-30 04:40:11 +00:00
|
|
|
|
from common.utils.logger import maxkb_logger
|
2026-10-21 07:48:54 +00:00
|
|
|
|
from common.utils.table_split import split_table_rows
|
2025-04-30 06:14:41 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def post_cell(cell_value):
|
|
|
|
|
|
return cell_value.replace('\n', '<br>').replace('|', '|')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def row_to_md(row):
|
|
|
|
|
|
return '| ' + ' | '.join(
|
|
|
|
|
|
[post_cell(cell) if cell is not None else '' for cell in row]) + ' |\n'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CsvSplitHandle(BaseSplitHandle):
|
2026-10-21 07:48:54 +00:00
|
|
|
|
def handle(self, file, pattern_list: List, with_filter: bool, limit: int, get_buffer, save_image, overlap: int = 0):
|
2025-04-30 06:14:41 +00:00
|
|
|
|
buffer = get_buffer(file)
|
|
|
|
|
|
paragraphs = []
|
|
|
|
|
|
file_name = os.path.basename(file.name)
|
|
|
|
|
|
result = {'name': file_name, 'content': paragraphs}
|
|
|
|
|
|
try:
|
2025-06-30 04:49:50 +00:00
|
|
|
|
if type(limit) is str:
|
|
|
|
|
|
limit = int(limit)
|
2025-04-30 06:14:41 +00:00
|
|
|
|
reader = csv.reader(io.TextIOWrapper(io.BytesIO(buffer), encoding=detect(buffer)['encoding']))
|
|
|
|
|
|
try:
|
|
|
|
|
|
title_row_list = reader.__next__()
|
|
|
|
|
|
title_md_content = row_to_md(title_row_list)
|
|
|
|
|
|
title_md_content += '| ' + ' | '.join(
|
|
|
|
|
|
['---' if cell is not None else '' for cell in title_row_list]) + ' |\n'
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
return result
|
|
|
|
|
|
if len(title_row_list) == 0:
|
|
|
|
|
|
return result
|
2026-10-21 07:48:54 +00:00
|
|
|
|
paragraphs.extend(split_table_rows(title_md_content, (row_to_md(row) for row in reader), limit, overlap))
|
2025-04-30 06:14:41 +00:00
|
|
|
|
return result
|
|
|
|
|
|
except Exception as e:
|
2025-06-30 04:40:11 +00:00
|
|
|
|
maxkb_logger.error(f"Error processing CSV file {file.name}: {e}, {traceback.format_exc()}")
|
2025-04-30 06:14:41 +00:00
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
def get_content(self, file, save_image):
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def support(self, file, get_buffer):
|
|
|
|
|
|
file_name: str = file.name.lower()
|
|
|
|
|
|
if file_name.endswith(".csv"):
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|