File size: 2,307 Bytes
68e8c03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Divisão de textos em chunks com sobreposição preservando metadados."""

from dataclasses import dataclass

from src.document_loader import DocumentPage


@dataclass(frozen=True)
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