Download src/text_splitter.py from AdryanAzul/DocuMindAI_RAG_Application: direct link, hf CLI and curl.
- Browser
- Download file 2.31 kB
-
https://huggingface.co/spaces/AdryanAzul/DocuMindAI_RAG_Application/resolve/main/src/text_splitter.py
- Command line
-
hf download hf://spaces/AdryanAzul/DocuMindAI_RAG_Application/src/text_splitter.py
-
curl -L -o text_splitter.py https://huggingface.co/spaces/AdryanAzul/DocuMindAI_RAG_Application/resolve/main/src/text_splitter.py
2.31 kB
| """Divisão de textos em chunks com sobreposição preservando metadados.""" | |
| from dataclasses import dataclass | |
| from src.document_loader import DocumentPage | |
| class TextChunk: | |
| """Representa um trecho de texto indexável com metadados de origem.""" | |
| text: str | |
| source: str | |
| page: int | |
| chunk_index: int | |
| def split_documents( | |
| pages: list[DocumentPage], | |
| chunk_size: int = 800, | |
| chunk_overlap: int = 150, | |
| ) -> list[TextChunk]: | |
| """Divide uma lista de páginas em chunks menores com sobreposição. | |
| Args: | |
| pages: Páginas extraídas pelo document_loader. | |
| chunk_size: Tamanho máximo de caracteres por chunk. | |
| chunk_overlap: Quantidade de caracteres sobrepostos entre chunks consecutivos. | |
| Returns: | |
| Lista de TextChunk pronta para geração de embeddings. | |
| Raises: | |
| ValueError: Se chunk_size <= 0 ou chunk_overlap < 0 ou chunk_overlap >= chunk_size. | |
| """ | |
| if chunk_size <= 0: | |
| raise ValueError("chunk_size deve ser maior que zero.") | |
| if chunk_overlap < 0 or chunk_overlap >= chunk_size: | |
| raise ValueError("chunk_overlap deve ser >= 0 e menor que chunk_size.") | |
| chunks: list[TextChunk] = [] | |
| global_index = 0 | |
| for page in pages: | |
| normalized = " ".join(page.text.split()) | |
| if not normalized: | |
| continue | |
| start = 0 | |
| text_length = len(normalized) | |
| while start < text_length: | |
| end = min(start + chunk_size, text_length) | |
| # Tenta quebrar no último espaço para não cortar palavras ao meio | |
| if end < text_length: | |
| last_space = normalized.rfind(" ", start, end) | |
| if last_space > start + chunk_size // 2: | |
| end = last_space | |
| chunk_text = normalized[start:end].strip() | |
| if chunk_text: | |
| chunks.append( | |
| TextChunk( | |
| text=chunk_text, | |
| source=page.source, | |
| page=page.page, | |
| chunk_index=global_index, | |
| ) | |
| ) | |
| global_index += 1 | |
| if end >= text_length: | |
| break | |
| start = max(end - chunk_overlap, start + 1) | |
| return chunks | |