Spaces:
Sleeping
Sleeping
Upload src/labdaps/ingestion/chunker.py with huggingface_hub
Browse files
src/labdaps/ingestion/chunker.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from src.labdaps.ingestion.pdf_extractor import RawPage
|
| 3 |
+
from src.labdaps.config import CHUNK_SIZE_CHARS, CHUNK_OVERLAP_CHARS, MIN_CHUNK_CHARS
|
| 4 |
+
|
| 5 |
+
SEPARATORS = ["\n\n\n", "\n\n", "\n", ". ", "! ", "? ", "; ", ", ", " ", ""]
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class Chunk:
|
| 10 |
+
text: str
|
| 11 |
+
source_file: str
|
| 12 |
+
page_number: int
|
| 13 |
+
chunk_index: int
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _split_text(text: str, size: int, overlap: int) -> list[str]:
|
| 17 |
+
if len(text) <= size:
|
| 18 |
+
return [text]
|
| 19 |
+
|
| 20 |
+
chunks = []
|
| 21 |
+
for sep in SEPARATORS:
|
| 22 |
+
if sep == "":
|
| 23 |
+
pieces = [text[i:i+size] for i in range(0, len(text), size - overlap)]
|
| 24 |
+
return [p for p in pieces if len(p) >= MIN_CHUNK_CHARS]
|
| 25 |
+
|
| 26 |
+
parts = text.split(sep)
|
| 27 |
+
if len(parts) == 1:
|
| 28 |
+
continue
|
| 29 |
+
|
| 30 |
+
current = ""
|
| 31 |
+
for part in parts:
|
| 32 |
+
candidate = current + (sep if current else "") + part
|
| 33 |
+
if len(candidate) <= size:
|
| 34 |
+
current = candidate
|
| 35 |
+
else:
|
| 36 |
+
if len(current) >= MIN_CHUNK_CHARS:
|
| 37 |
+
chunks.append(current)
|
| 38 |
+
if current and overlap > 0:
|
| 39 |
+
overlap_text = current[-overlap:]
|
| 40 |
+
current = overlap_text + (sep if overlap_text else "") + part
|
| 41 |
+
else:
|
| 42 |
+
current = part
|
| 43 |
+
|
| 44 |
+
if len(current) >= MIN_CHUNK_CHARS:
|
| 45 |
+
chunks.append(current)
|
| 46 |
+
|
| 47 |
+
if chunks:
|
| 48 |
+
return chunks
|
| 49 |
+
|
| 50 |
+
return [text] if len(text) >= MIN_CHUNK_CHARS else []
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def chunk_pages(pages: list[RawPage]) -> list[Chunk]:
|
| 54 |
+
chunks = []
|
| 55 |
+
global_index = 0
|
| 56 |
+
for page in pages:
|
| 57 |
+
for text in _split_text(page.text, CHUNK_SIZE_CHARS, CHUNK_OVERLAP_CHARS):
|
| 58 |
+
chunks.append(Chunk(
|
| 59 |
+
text=text,
|
| 60 |
+
source_file=page.source_file,
|
| 61 |
+
page_number=page.page_number,
|
| 62 |
+
chunk_index=global_index,
|
| 63 |
+
))
|
| 64 |
+
global_index += 1
|
| 65 |
+
return chunks
|