2024-03-29 10:28:05 +00:00
|
|
|
|
# coding=utf-8
|
|
|
|
|
|
"""
|
|
|
|
|
|
@project: maxkb
|
|
|
|
|
|
@Author:虎
|
|
|
|
|
|
@file: text_split_handle.py
|
|
|
|
|
|
@date:2024/3/27 18:19
|
|
|
|
|
|
@desc:
|
|
|
|
|
|
"""
|
|
|
|
|
|
import re
|
|
|
|
|
|
from typing import List
|
|
|
|
|
|
|
2024-04-02 11:32:04 +00:00
|
|
|
|
from charset_normalizer import detect
|
2024-03-29 10:28:05 +00:00
|
|
|
|
|
|
|
|
|
|
from common.handle.base_split_handle import BaseSplitHandle
|
|
|
|
|
|
from common.util.split_model import SplitModel
|
|
|
|
|
|
|
2024-04-09 10:05:50 +00:00
|
|
|
|
default_pattern_list = [re.compile('(?<=^)# .*|(?<=\\n)# .*'),
|
|
|
|
|
|
re.compile('(?<=\\n)(?<!#)## (?!#).*|(?<=^)(?<!#)## (?!#).*'),
|
|
|
|
|
|
re.compile("(?<=\\n)(?<!#)### (?!#).*|(?<=^)(?<!#)### (?!#).*"),
|
|
|
|
|
|
re.compile("(?<=\\n)(?<!#)#### (?!#).*|(?<=^)(?<!#)#### (?!#).*"),
|
|
|
|
|
|
re.compile("(?<=\\n)(?<!#)##### (?!#).*|(?<=^)(?<!#)##### (?!#).*"),
|
|
|
|
|
|
re.compile("(?<=\\n)(?<!#)###### (?!#).*|(?<=^)(?<!#)###### (?!#).*")]
|
2024-03-29 10:28:05 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class TextSplitHandle(BaseSplitHandle):
|
|
|
|
|
|
def support(self, file, get_buffer):
|
|
|
|
|
|
buffer = get_buffer(file)
|
|
|
|
|
|
file_name: str = file.name.lower()
|
|
|
|
|
|
if file_name.endswith(".md") or file_name.endswith('.txt'):
|
|
|
|
|
|
return True
|
2024-04-02 11:32:04 +00:00
|
|
|
|
result = detect(buffer)
|
2024-03-29 10:28:05 +00:00
|
|
|
|
if result['encoding'] != 'ascii' and result['confidence'] > 0.5:
|
|
|
|
|
|
return True
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
def handle(self, file, pattern_list: List, with_filter: bool, limit: int, get_buffer):
|
|
|
|
|
|
buffer = get_buffer(file)
|
|
|
|
|
|
if pattern_list is not None and len(pattern_list) > 0:
|
|
|
|
|
|
split_model = SplitModel(pattern_list, with_filter, limit)
|
|
|
|
|
|
else:
|
|
|
|
|
|
split_model = SplitModel(default_pattern_list, with_filter=with_filter, limit=limit)
|
|
|
|
|
|
try:
|
2024-04-02 11:32:04 +00:00
|
|
|
|
content = buffer.decode(detect(buffer)['encoding'])
|
2024-03-29 10:28:05 +00:00
|
|
|
|
except BaseException as e:
|
|
|
|
|
|
return {'name': file.name,
|
|
|
|
|
|
'content': []}
|
|
|
|
|
|
return {'name': file.name,
|
|
|
|
|
|
'content': split_model.parse(content)
|
|
|
|
|
|
}
|