2024-09-25 13:46:23 +08:00
|
|
|
import os
|
|
|
|
|
from pathlib import Path
|
2024-09-26 22:45:02 +08:00
|
|
|
from llama_index.core import Document
|
2024-09-25 13:46:23 +08:00
|
|
|
from llama_index.core.node_parser import SimpleFileNodeParser
|
2024-09-26 22:45:02 +08:00
|
|
|
from llama_index.core.node_parser import SentenceSplitter
|
|
|
|
|
from llama_index.readers.file import FlatReader, DocxReader
|
2024-09-25 13:46:23 +08:00
|
|
|
|
|
|
|
|
from src.utils import hashstr
|
|
|
|
|
|
2024-09-26 22:45:02 +08:00
|
|
|
def chunk(text_or_path, params=None):
|
2024-09-25 13:46:23 +08:00
|
|
|
params = params or {}
|
|
|
|
|
chunk_size = int(params.get("chunk_size", 500))
|
|
|
|
|
chunk_overlap = int(params.get("chunk_overlap", 20))
|
|
|
|
|
splitter = SentenceSplitter(
|
|
|
|
|
chunk_size=chunk_size,
|
|
|
|
|
chunk_overlap=chunk_overlap,
|
|
|
|
|
)
|
|
|
|
|
|
2024-09-26 22:45:02 +08:00
|
|
|
if os.path.isfile(text_or_path) and "uploads" in text_or_path:
|
|
|
|
|
parser = SimpleFileNodeParser()
|
2024-09-29 16:13:06 +08:00
|
|
|
file_type = Path(text_or_path).suffix.lower()
|
2024-09-26 22:45:02 +08:00
|
|
|
if file_type in [".txt", ".json", ".md"]:
|
|
|
|
|
docs = FlatReader().load_data(Path(text_or_path))
|
|
|
|
|
elif file_type in [".docx"]:
|
|
|
|
|
docs = DocxReader().load_data(Path(text_or_path))
|
|
|
|
|
else:
|
|
|
|
|
raise ValueError(f"Unsupported file type `{file_type}`")
|
|
|
|
|
|
|
|
|
|
if params.get("use_parser"):
|
|
|
|
|
nodes = parser.get_nodes_from_documents(docs)
|
|
|
|
|
else:
|
|
|
|
|
nodes = splitter.get_nodes_from_documents(docs)
|
|
|
|
|
|
2024-09-25 13:46:23 +08:00
|
|
|
else:
|
2024-09-26 22:45:02 +08:00
|
|
|
docs = [Document(id_=hashstr(text_or_path), text=text_or_path)]
|
|
|
|
|
nodes = splitter.get_nodes_from_documents(docs)
|
2024-09-25 13:46:23 +08:00
|
|
|
|
2024-09-26 22:45:02 +08:00
|
|
|
return nodes
|